Python String rpartition() Method
rpartition() method splits the string at the last occurrence of the specified string separator
sep argument and returns a tuple containing three elements, the part before the separator, the separator itself, and the part after the separator.
sep: (Required) A string separator.
- Returns tuple that contains three elements
- The part before the separator as a first element, the separator itself as a second element, and the part after the separator as a third element if the specified separator is found.
- If the specified separator is not found, then returns the string itself as a first element and two empty string elements.
The following example demonstrates the simple use of the
mystr = 'Hello World' print(mystr.rpartition('o')) print(mystr.rpartition('l')) print(mystr.rpartition('W'))
('Hello W', 'o', 'rld') ('Hello Wor', 'l', 'd') ('Hello ', 'W', 'orld')
In the above example,
mystr.rpartition('o') splits a string from the last occurance of 'o' which is 'Hello World'.
In the same way,
mystr.rpartition('l') splits from last that is 'Hello World'.
rpartition() method search is case-sensitive. It treats 'Tutorials' and 'tutorials' as two separate words, as shown below.
mystr = 'TutorialsTeacher' print(mystr.rpartition('t')) print(mystr.rpartition('T'))
('Tu', 't', 'orialsTeacher') ('Tutorials', 'T', 'eacher')
In the above example, 't' and 'T' are treated as two different separators and so returns two different tuples. Note that if a separator string is found at the start of a string, then the first element of a returning tuple will be empty, as in the case of 'Tutorials' separator in the above example.
If the separator is not present in the string, then the tuple contains the original string and two empty strings, as shown below.
If the separator is an empty string, then the
rpartition() method will throw
ValueError, as shown below.
mystr = 'Hello World' print(mystr.rpartition('s')) mystr = 'Hello World' print(mystr.rpartition('')) # raises ValueError
('', '', 'Hello World') ValueError: empty separator