The Python string partition() method is used to split a string into three parts based on the first occurrence of a specified separator. It returns a tuple containing three elements: the part of the string before the separator, the separator itself, and the part of the string after the separator.
If the separator is not found in the string, the entire string is returned as the first element of the tuple, followed by two empty strings.
SyntaxFollowing is the basic syntax of the Python String partition() method −
string.partition(separator)Parameter
This method accepts a separator string as a parameter that specifies where to perform the split.
Return ValueThe method returns a tuple containing three elements: the part of the string before the first occurrence of the separator, the separator itself, and the part of the string after the first occurrence of the separator.
ExampleIn the following example, we are splitting the string "text" at the first occurrence of the space " " character using the partition() method −
text = "hello world" result = text.partition(' ') print(result)Output
The output obtained is as follows −
('hello', ' ', 'world')Example
This example shows that if the separator is not found in the string, the entire string is returned as the first element of the tuple, and the other two elements are empty strings −
text = "hello" result = text.partition(',') print(result)Output
Following is the output of the above code −
('hello', '', '')Example
Here, we split the string "text" at the first occurrence of the space character ' '. Since there are multiple space characters, only the first one is used as the separator −
text = "apple banana orange" result = text.partition(' ') print(result)Output
The result produced is as shown below −
('apple', ' ', 'banana orange')Example
Now, we are splitting the string "text" at the first occurrence of the newline character "\n" −
text = "Tutorials\nPoint\nEdTech" result = text.partition('\n') print(result)Output
We get the output as shown below −
('Tutorials', '\n', 'Point\nEdTech')
split_and_join.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4