This is a tutorial of the Python String partition() method. Learn to partition a given string into a 3-item tuple. (Left Part, Splitting Part, Right Part)
This method returns a 3-element tuple for a given string such that it contains three parts created after splitting the original string from the first occurrence of a given character or substring. The 3-element tuple so returned contains the part before the splitting part as the first element, the splitting part itself as the second element and the part of the string after the splitting part as the third element.
Note. The splitting part is also known as the separator.
In other words, this method does the 3-part partition of the given string and return the partitioned strings in the form of a 3-element Python Tuple.
As this method splits the string from the first occurrence of the separator string, if you want the string to be splitter from the last occurrence of the separator string, you can use the Python String rpartition() method instead.
Given below is the syntax for the Python String
stringPartitions = givenString.partition(separator)
This method takes only a single argument and that is the
separator. It is the part of the string from where the string actually breaks up or splits. It is a string type argument. Therefore, it can be a single character or a substring of the original string. It is mandatory to provide this argument.
str.partition() Return Value
It returns a tuple containing 3 items such that each item of this tuple is actually a part of the original string on which this method is applied.
- The first item of the tuple is the part of the string before the separator.
- The second item of the tuple is the separator itself.
- The third item of the tuple is the part of the string that comes after the separator in the original string.
Note. In case, the string has multiple occurrences of the splitting character, it splits the string from the first occurrence of the separator.
Example: Basic usage of the Python String partition() method
Here in the following example, we’ve applied the method
partition() on four different strings to illustrate its working.
string1 = "Welcome to WTMatter.com" #Separator Exists print(string1.partition(' to ')) string2 = "How are you?" #Separator Not Found print(string2.partition(' of ')) string3 = "this is super! is not it?" #Splits from first occurrence of 'is' print(string3.partition(' is ')) string4 = "Enjoy the tutorial!" #Splitting from space print(string4.partition(" "))
('Welcome', ' to ', 'WTMatter.com') ('How are you?', '', '') ('this', ' is ', 'super! is not it?') ('Enjoy', ' ', 'the tutorial!')
I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!