Python Reference ยท String Methods
Python str.rsplit() method
Reference for Python str.rsplit(): split a string into a list starting from the right, how maxsplit changes the result, and how it differs from split().
The str.rsplit() method splits a string into a list of substrings, like split(), but it counts splits from the right end. Without a limit the result is identical to split(). The difference only appears when you pass maxsplit.
Use it when you want to peel off the last one or two parts and keep the rest intact, such as splitting a name from its extension or a host from a trailing port.
print("a.b.c.d".rsplit(".", 1)) # ['a.b.c', 'd']
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.rsplit() str.rsplit(sep=None, maxsplit=-1)
| Name | Description |
|---|---|
sep |
Optional. The separator string. With None (the default) the string is split on runs of whitespace and empty strings are discarded. |
maxsplit |
Optional. The maximum number of splits, made from the right. -1 (the default) means no limit. |
Return value: a list of strings, in the original left-to-right order. With maxsplit, the list has at most maxsplit + 1 items.
Raises: ValueError if sep is an empty string; TypeError for wrong argument types.
Usage notes
- Same as
split()withoutmaxsplit. The two only differ when the limit is reached:splitkeeps the unsplit rest on the right,rspliton the left. - Result order is not reversed. The pieces stay in their natural order.
- Explicit separator keeps empty strings.
"a,,b".rsplit(",")gives['a', '', 'b']. Whitespace mode drops them. - Not found: a one-item list with the whole string.
"".rsplit(",")is[''], but"".rsplit()is[]. - Unpacking with a limit is risky if the separator might be missing, because the list is then too short.
rpartition()always returns three items. sepis literal, not a regular expression. Usere.split()for patterns.- Both parameters can be keywords (
rsplit(sep=",", maxsplit=1)). - Also on
bytesandbytearray.