Python partition
Python String partition Method
The Python partition method divides a string based on the specified parameter. It performs the split at the initial occurrence of the parameter and yields a tuple as the result. This tuple consists of three components: the substring preceding the separator, the separator itself, and the substring that follows the separator.
It yields an empty tuple that contains only the separator when the separator is not present.
Syntax of Python String partition Method
The method signature is given below.
partition(sep)
Parameters
- sep: A parameter of type string that acts as a delimiter for the string.
Return
It returns a tuple, A 3-Tuple.
Different Examples for Python String partition Method
Let’s examine a few examples of the partition(sep) method to gain a clearer understanding of how it operates.
Example 1
First, let's see simple use of partition method.
# Python partition() method example
# Variable declaration
str = "Pyton is a programming language"
# Calling function
str2 = str.partition("is")
# Displaying result
print(str2)
# when seperate from the start
str2 = str.partition("Python")
print(str2)
# when seperate is the end
str2 = str.partition("language")
print(str2)
# when seperater is a substring
str2 = str.partition("av")
print(str2)
Example 2
In the event that the separator cannot be located, it yields a tuple that includes the original string along with two empty strings. Refer to the example provided below.
# Python partition() method example
# Variable declaration
str = "Python is a programming language"
# Calling function
str2 = str.partition("not")
# Displaying result
print(str2)
Output:
('Python is a programming language', '', '')