rpartition() works like partition(), but it searches from the right, and cuts the string at the last appearance of the separator. It always returns a tuple of three items: the part before, the separator, and the part after.
If the separator is not found, you still get three items, but the whole string comes last: two empty strings, then the text. That detail matters when you unpack the result. The original string is not changed.
text.rpartition() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the separator to look for. It is required, and it must be a string.
python
before, sep, after = text.rpartition(sep)
Call
What it does
"a/b/c".rpartition("/")
Returns ('a/b', '/', 'c'). The text is cut at the last slash.
"key=a=b".rpartition("=")
Returns ('key=a', '=', 'b'). Only the last equals sign is used.
"novalue".rpartition("=")
Returns ('', '', 'novalue'). The separator is missing, so the whole text is the last item.
To cut at the first separator use partition(). To get a list and limit the cuts from the right, use rsplit(). To only find the position of the last match, use rfind().
Library declarations
python
str.rpartition(sep) -> tuple
# returns: (before, sep, after), a tuple of three strings
Parameters
Parameter
Description
sep
Required. The text to split at. It must be a non-empty string, otherwise ValueError is raised.
Return Value
Return Value
Description
tuple
A tuple of three strings: the part before the last separator, the separator, and the part after. If the separator is not found, it is ('', '', text).
Python Examples
Example 1 — Split a Folder From a File Name
Cut a path at its last slash, and compare with partition().
The last dot. The text is cut only at the final dot, so 3.12 stays together.
The last part.patch is the string '4'.
Convert, then add.int(patch) + 1 turns the text into a number and adds one, which gives 5.
Frequently Asked Questions
It splits a string at the last occurrence of a separator and returns a tuple of three strings: the part before, the separator, and the part after.
It returns a tuple of two empty strings followed by the whole text, such as ("", "", text).
partition() uses the first separator and rpartition() uses the last one. If the separator is missing, partition() puts the text first and rpartition() puts it last.
Use name.rpartition(".")[2], but check that the middle item is not empty first, because a name without a dot would give the whole name.
No. Strings are immutable, so rpartition() returns a new tuple and leaves the string as it is.