str.rsplit()
Split from the right — only meaningfully different from split when maxsplit is used.
Demo
rsplit only differs from split when maxsplit is set. With maxsplit=N, the LAST N delimiters produce splits — the head accumulates everything before those into a single piece. sep=None (the empty demo input) collapses whitespace runs AND trims ends, exactly like split. Empty sep string (only when specified explicitly) raises ValueError.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sep | str | None | no (None) | Delimiter. None (default) splits on any whitespace runs and strips leading/trailing whitespace. Empty string raises ValueError. |
| maxsplit | int | no (-1) | Maximum number of splits from the RIGHT. -1 (default) means no limit. When set, the head keeps the un-split remainder as one piece. |
Return value
list[str] — A list of the parts. With no maxsplit (or -1), identical to split. With maxsplit set, splits at most maxsplit times FROM THE RIGHT — the last N pieces get their own slots, the head keeps everything else.
Common patterns
user, host = addr.rsplit("@", 1)
directory, name = path.rsplit("/", 1)
head, last_but_one, last = line.rsplit(",", 2)
Examples
Pitfalls
"a,b,c".rsplit(",") "a,b,c".split(",")
"a,b,c".rsplit(",", 1)
"hello".rsplit("")
"hello world".rsplit(None, 1)
" a b ".rsplit(" ")
" a b ".rsplit(None)
"a,b,c,d".rsplit(",", 3) # expected 3 pieces?
"a,b,c,d".rsplit(",", 2)
When to use
- Splitting off the last N fields while keeping the head intact
- Splitting emails, URLs, or paths where the trailing part matters
- Any "head + tail" parsing where the delimiter appears earlier in the head too
- No maxsplit → just use split, they are identical
- Two-piece split at the first occurrence → split(sep, 1) instead
- Fixed-shape three-piece result → rpartition
- Splitting on regex → re.split
Notes
FAQ
When maxsplit is set and you want the LAST N pieces isolated, with the head kept as a single string. Classic cases: an email where the local part could contain "@", a path where the base name is at the end, a compound identifier where you only want the suffix.