Python String rpartition() Method

Splits the string into a three-part tuple

Usage

The rpartition() method splits the string at the last occurrence of separator, and returns a tuple containing three items.

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

rpartition() Vs partition()

Unlike rpartition(), The partition() method splits the string at the first occurrence of separator. Otherwise, both methods work exactly the same.

Syntax

string.rpartition(separator)

Python string rpartition() method parameters
ParameterConditionDescription
separatorRequiredAny substring to split the sting with.

Basic Example

# Split the string on 'and'
S = 'Do it now and keep it simple'
x = S.rpartition('and')
print(x)
# Prints ('Do it now ', 'and', ' keep it simple')

No Match Found

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

S = 'Do it now and keep it simple'
x = S.rpartition('or')
print(x)
# Prints ('', '', 'Do it now and keep it simple')

Multiple Matches

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

S = 'Do it now and keep it simple'
x = S.rpartition('it')
print(x)
# Prints ('Do it now and keep ', 'it', ' simple')