Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
string
partition
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
string
partition
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring