The rpartition()
method in Python is a string method that splits a string into three parts based on a specified separator. It starts from the end of the string and searches for the last occurrence of the separator. It returns a tuple containing the part before the separator, the separator itself, and the part after the separator.
Parameter Values
Parameter | Description |
---|---|
sep | The separator to look for in the string. The string is partitioned around the last occurrence of this parameter. |
Return Values
The rpartition()
method returns a tuple of three elements: two str
s and the separator.
How to Use rpartition()
in Python
The rpartition()
method searches for a specified separator and splits the string into a 3-tuple of substrings. The search starts from the end of the string.
text = 'Hello, world!'
result = text.rpartition(', ')
print(result)
If the separator is not found in the string, the method returns a 3-tuple where the first two elements are empty strings, and the last element is the original string.
text = 'Python programming'
result = text.rpartition(':')
print(result)
The rpartition()
method is useful for splitting a string into prefix, separator, and suffix based on the last occurrence of the separator.
url = 'https://www.example.com/index.html'
result = url.rpartition('/')
print(result)