Skip to content

Python String rpartition() Method

How the Python rpartition() method splits a string at its last occurrence of a separator and returns a tuple with three elements: before, separator, and after.

The String rpartition() method splits the string at the last occurrence of the separator and returns a tuple containing three elements:

  • The part of the string before the separator
  • The separator itself
  • The part of the string after the separator

Syntax

my_string.rpartition(separator)

rpartition() Parameters

Python String rpartition() method parameters:

Parameter Condition Description
separator Required Any substring to split the string with.

rpartition() Return Value

Python String rpartition() method returns a tuple of three elements containing:

  • if the separator parameter is found in the string
    • the part before the separator
    • the separator parameter
    • the part after the separator
  • if the separator parameter is not found in the string
    • two empty strings and the string itself

Examples

Example : Partition of a String with rpartition()

The rpartition() method returns a tuple of three elements.

In this example, the separator 'for' is found, and so a tuple made of the part before the separator, the separator and the part after the separator is returned:

my_str = 'This is an example for rpartition() method'
result = my_str.rpartition('for')
print(result) # Output: ('This is an example ', 'for', ' rpartition() method')

output

('This is an example ', 'for', ' rpartition() method')

Example 2: Partition of a String when Separator is Not Found

If the separator is not found, the method returns a tuple containing the string itself, followed by two empty strings.

my_str = 'This is an example for rpartition() method'
result = my_str.rpartition('and')
print(result) # Output: ('', '', 'This is an example for rpartition() method')

output

('', '', 'This is an example for rpartition() method')

Example :

Partition of a String when Multiple Occurrences of Separator are present

If the separator is present multiple times, the method splits the string at the first occurrence.

my_str = 'This is an example for rpartition() method'
result = my_str.rpartition('is')
print(result) # Output: ('This ', 'is', ' an example for rpartition() method')

output

('This ', 'is', ' an example for rpartition() method')
Navigation