Python String rpartition() Function
The String rpartition()
method splits the string at the last occurrence of the separator
and returns a tuple containing three elements:
- The part of the string before the separator
- The separator itself
- The part of the string after the separator
Note that:
partition()
method splits the string at the first occurrence of the separatorrpartition()
method splits the string at the last occurrence of the separator
If there is only one occurrence of the separator, both methods work exactly the same.
Syntax
my_string.rpartition(separator)
rpartition() Parameters
Python String rpartition()
function parameters:
Parameter | Condition | Description |
---|---|---|
separator | Required | Any substring to split the string with. |
rpartition() Return Value
Python String rpartition()
function returns a tuple of three elements containing:
- if the
separator
parameter is found in the string- the part before the separator
- the separator parameter
- the part after the separator
- if the
separator
parameter is not found in the string- two empty strings and the string itself
Examples
Example : Partition of a String with rpartition()
The rpartition()
function returns a tuple of three elements.
In this example, the separator 'for'
is found, and so a tuple made of the part before the separator, the separator and the part after the separator is returned:
my_str = 'This is an example for rpartition() method'
result = my_str.rpartition('for')
print(result) # Output: ('This is an example ', 'for', ' rpartition() method')
output
('This is an example ', 'for', ' rpartition() method')
Example 2: Partition of a String when Separator is Not Found
If the separator
is not found, the method returns a tuple containing the string itself, followed by two empty strings.
my_str = 'This is an example for rpartition() method'
result = my_str.rpartition('and')
print(result) # Output: ('', '', 'This is an example for rpartition() method')
output
('', '', 'This is an example for rpartition() method')
Example :
Partition of a String when Multiple Occurrences of Separator are present
If the separator
is present multiple times, the method splits the string at the first occurrence.
my_str = 'This is an example for rpartition() method'
result = my_str.rpartition('is')
print(result) # Output: ('This ', 'is', ' an example for rpartition() method')
output
('This ', 'is', ' an example for rpartition() method')