Python String rpartition() Method

The 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.

Syntax:

str.rpartition(sep)

Parameters:

sep: (Required) A string separator.

Return Value:

  1. Returns tuple that contains three elements
  2. 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.
  3. 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 rpartition() method.

Example: rpartition()
mystr = 'Hello World'
print(mystr.rpartition('o'))
print(mystr.rpartition('l'))
print(mystr.rpartition('W'))
Output
('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'.

The rpartition() method search is case-sensitive. It treats 'Tutorials' and 'tutorials' as two separate words, as shown below.

Example: rpartition()
mystr = 'TutorialsTeacher'
print(mystr.rpartition('t'))
print(mystr.rpartition('T'))
Output
('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.

Example: rpartition()
mystr = 'Hello World'
print(mystr.rpartition('s'))

mystr = 'Hello World'
print(mystr.rpartition('')) # raises ValueError
Output
('', '', 'Hello World')
ValueError: empty separator
Want to check how much you know Python?