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

Example: Split the string on ‘and’

S = 'Do it now and keep it simple'
x = S.rpartition('and')
print(x)    # ('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.

Example: If the separator is not found

S = 'Do it now and keep it simple'
x = S.rpartition('or')
print(x)    # ('', '', '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.

Example: Split the string at the last occurrence of ‘it’

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