Python string rpartition method explanation with example

Python string rpartition() method:

rpartition method of python string can be used to split the string at some specific separator. It splits the string at the last occurrence of the provided separator and it returns a tuple holding the split strings.

Let’s learn how to use rpartition with examples.

Definition of rpartition:

The str.rpartition method is defined as like below:

str.rpartition(sep)

Here,

  • sep is the separator used for the split.

It will split the string str at the last occurrence of the separator sep. It will return a tuple holding three elements: the substring before the separator, the separator and the substring after the separator.

If we pass an empty string, it will return a tuple of three elements: two empty strings and the string itself.

Let’s start with an example to demonstrate how rpartition works:

Example of rpartition:

Consider the below example:

given_str = 'Apple Orange'

print(given_str.rpartition('a')) # ('Apple Or', 'a', 'nge')
print(given_str.rpartition('A')) # ('', 'A', 'pple Orange')
print(given_str.rpartition('e')) # ('Apple Orang', 'e', '')
print(given_str.rpartition('p')) # ('Ap', 'p', 'le Orange')
  • The first line is partitioning the string given_str at a. rpartition is case sensitive, so it will not break it at ‘A’, it will break it at ‘a’ instead.
  • The second line is partitioning the string at ‘A’. So, the first string is an empty string in the tuple.
  • The third line is partitioning the string at ‘e’. So, the third string is an empty string in the tuple.
  • The fourth line is partitioning the string at ‘p’. It has two ‘p’ and it picks the second ‘p’.

Example of rpartition with an empty string:

The below program uses an empty string with rpartition:

given_str = ''

print(given_str.rpartition('a'))
print(given_str.rpartition('p'))

It will return a tuple holding three empty strings.

Python string rpartition example

ValueError:

If the separator is an empty string, it throws ValueError:

given_str = 'hello'

print(given_str.rpartition(''))

It will an empty separator ValueError as like below:

Traceback (most recent call last):
  File "example.py", line 3, in <module>
    print(given_str.rpartition(''))
ValueError: empty separator

But, if you pass a tab character, it works:

given_str = 'hello'

print(given_str.rpartition('    '))

It returns:

('', '', 'hello')

You might also like: