Python String rpartition() Method

The rpartition() method splits a string into three parts based on the last occurrence of a specified separator. It returns a tuple containing the part before the separator, the separator itself, and the part after the separator.

Syntax

string.rpartition(separator)

Parameter

separator (required): The string to search for and split upon.

Return Value

Returns a tuple with three elements:

(1) The part of the string before the last occurrence of the separator.

(2) The separator itself (if found).

(3) The part of the string after the last occurrence of the separator.

If the separator is not found, it returns a tuple where the first two elements are empty strings, and the third element is the original string itself.

Examples

Partitioning a String at the Last Occurrence of the Substring

text = "Python is awesome. It is very easy."
result = text.rpartition("is")
print(result) # Output: ('Python is awesome. It ', 'is', ' very easy.')

If the separator appears only once in the string, partition() and rpartition() produces the same output.

Separator Not Found

If the separator is not found in the string, the rpartition() method returns a tuple where the first two elements are empty strings, and the third element is the original string itself.

text = "Python is awesome. It is very easy."
result = text.rpartition("and")
print(result) # Output: ('', '', 'Python is awesome. It is very easy.')

partition() vs rpartition()

The key difference between partition() an rpartition() is:

partition(): Splits the string at the first occurrence of a specified separator (from the left).

rpartition(): Splits the string at the last occurrence of a specified separator (from the right).