Python String rpartition()
Python String.rpartition() is used to partition this string into three parts. The rpartition() method takes a value
as argument, searches for it from the end to the start of the string, and if found, splits the string at this value
, and returns the part before this value as first, part, this value
as second part, and the rest of the string as third part. These splits are returned in a tuple.
In this tutorial, we will learn the syntax and examples for rpartition() method of String class.
Syntax
The syntax to call rpartition() method on string x
in Python is
x.rpartition(value)
where
Parameter | Required / Optional | Description |
---|---|---|
value | Required | A string. Specifies the value at which the string has to be split. Search for this value from right to left of the calling string. |
Examples
In the following program, we take a string 'hello world apple banana'
, and partition this string at the last occurrence of value='world'
.
Example.py
x = 'hello world apple world banana'
result = x.rpartition('world')
print('Original String : ', x)
print('Partitions : ', result)
Output
Original String : hello world apple world banana
Partitions : ('hello world apple ', 'world', ' banana')
If the given argument is not present in the string, then the third item in the resulting tuple is the original string; first and second items are empty.
Example.py
x = 'hello world apple world banana'
result = x.rpartition('cherry')
print('Original String : ', x)
print('Partitions : ', result)
Output
Original String : hello world apple world banana
Partitions : ('', '', 'hello world apple world banana')
Conclusion
In this Python Tutorial, we learned how to split a string into partitions using rpartition() method, with examples.