What is the string.rpartition() method in Python?

What is rpartition?

The rpartition method splits the last occurrence of string_B in string_A and returns a tuplea data structure in Python that stores an ordered sequence of values with 3 items.

Partitioning concept in rpartition

  • The first item contains the part of the string before string_B.

  • The second item contains string_B itself.

  • The third item contains the part of the string after string_B.

Syntax


string_A.rpartition(string_B)

Return value

If string_B is not present in string_A, a tuple with the two empty strings and string_A is returned, i.e., ('', '', string_A).

Code

Example 1

string = "this test is a testing"
tup = string.rpartition('test')
print(tup)

Explanation

In the code above, we create a string, this test is a testing, and call rpartition('test'), which splits the string at the last occurrence of the test substring. This returns a tuple that contains 3 items.

  • 1st item: The part of the string before the last occurrence of the test substring. In our case, it is this test is a .

  • 2nd item: The separator string itself. In our case, it is test.

  • 3rd item: The part of the string after the last occurrence of the test substring. In our case, it is ing.

Example 2

string = "this test is a test"
tup = string.rpartition('best')
print(tup)

Explanation

In the code above, we create a string, this test is a testing, and call rpartition('best'). But the string has no best substring, so the rpartition method will return a tuple that contains 3 items.

  • 1st and 2nd items: empty strings.

  • 3rd item: The source string. In our case, it is this test is a testing.

Free Resources