Python String rpartition() Method



The Python string rpartition() method is used to split a string into three parts based on the last occurrence of a specified separator. It is similar to the partition() method, but it searches for the separator from the right end of the string and returns the last occurrence of the separator.

It is generally used in scenarios where you need to extract information from strings in reverse order.

Syntax

Following is the basic syntax of the Python String rpartition() method −

string.partition(separator)

Parameter

This method accepts a separator string as a parameter that specifies where to perform the split.

Return Value

The method returns a tuple containing three elements: the part of the string before the last occurrence of the separator, the separator itself, and the part of the string after the last occurrence of the separator.

Example

In the following example, we are splitting the string "text" at the last occurrence of the space "  " character using the rpartition() method −

text = "hello world"
result = text.rpartition(' ')
print(result)   

Output

The output obtained is as follows −

('hello', ' ', 'world')

Example

This example shows that if the separator is not found in the string, the entire string is returned as the third element of the tuple, and the other two elements are empty strings −

text = "hello"
result = text.rpartition(',')
print(result)       

Output

Following is the output of the above code −

('', '', 'hello')

Example

Here, we split the string "text" at the last occurrence of the space character ' '. Since there are multiple space characters, only the last one is used as the separator −

text = "apple banana orange"
result = text.rpartition(' ')
print(result)    

Output

The result produced is as shown below −

('apple banana', ' ', 'orange')

Example

Now, we are splitting the string "text" at the last occurrence of the newline character "\n" −

text = "Tutorials\nPoint\nEdTech"
result = text.rpartition('\n')
print(result) 

Output

We get the output as shown below −

('Tutorials\nPoint', '\n', 'EdTech')
split_and_join.htm
Advertisements