Python String rpartition() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String rpartition() method

The rpartition() method in Python searches for the last occurence of the specified string and splits the string into a tuple containing three elements.

  1. The first element - Contains the part before the specified string.
  2. The second element - Contains the specified string.
  3. The third element - Contains the part after the string.
Syntax of rpartition() method
string.rpartition(value)

value: The substring to partition on
Example 1

Code

str1 = "Pylenin loves Python"
print(str1.rpartition("loves"))

Output

('Pylenin ', 'loves', ' Python')
Example 2 - When the substring doesn’t exist

Code

str1 = "Pylenin loves Python"
print(str1.rpartition("cake"))

Output

('', '', 'Pylenin loves Python')

As you can see, it returned the entire string as the last element of the tuple and the first 2 elements are empty strings. The rpartition() method doesn’t throw any error if it is unable to find the substring.

Example 3 - When the substring occurs multiple times

Code

str1 = "Pylenin loves Python and Python loves Pylenin"
print(str1.rpartition("Python"))

Output

('Pylenin loves Python and ', 'Python', ' loves Pylenin')

The rpartition() method separates at the last occurence of the provided substring.

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide