str.rpartition()
Split the string at the LAST occurrence of sep, returning a fixed-shape three-tuple. The mirror of str.partition.
Demo
rpartition splits at the LAST occurrence of sep — the mirror of partition. Always returns exactly three strings. When the separator is not found, the "original" slot moves: partition puts it at index 0, rpartition puts it at index 2. That asymmetry matches the direction each method scans from.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sep | str | yes | Substring to split on. Empty string raises ValueError. Last occurrence only. |
Return value
tuple[str, str, str] — Always a 3-tuple (before, sep, after). If sep is not found: ("", "", original_string) — note the original is in slot 2, unlike partition where it lands in slot 0.
Common patterns
stem, _, ext = filename.rpartition(".")
dir_, _, base = path.rpartition("/")
head, sep, tail = s.rpartition(":") tag = tail if sep else "default"
Examples
Pitfalls
before, _, _ = "hello".rpartition("=") # before is ""
before, sep, after = s.rpartition("=") value = after if sep else before
"a=b=c".rpartition("=")
"a=b=c".split("=")
"hello".rpartition("")
if sep: a, s, b = text.rpartition(sep)
"a.tar.gz".rpartition(".")[2]
stem, sep, ext = s.rpartition(".") full_ext = sep + ext # ".gz"
When to use
- Splitting a filename at its final dot
- Extracting basename from a path (rpartition("/") or ("\\"))
- "Take the tail" parsing where the delimiter may appear multiple times
- Getting a fixed-shape return you can always unpack into three names
- Full N-way split → split
- First-occurrence split → partition
- Regex-based splits → re.split
- Filename splits where you care about ".tar.gz" as a compound → use pathlib's suffixes
Notes
FAQ
They scan from opposite directions. partition splits at the FIRST occurrence and puts the original in slot 0 when missing. rpartition splits at the LAST occurrence and puts the original in slot 2 when missing. Pick based on where the delimiter of interest sits.