Skip to content
Tutorials Center
My learning

Topics

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.

Python
print("a.b.c.d".rsplit(".", 1))   # ['a.b.c', 'd']

Try it

Python Limiting splits from the right

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.

Python Whitespace mode and edge cases

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

Python
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() without maxsplit. The two only differ when the limit is reached: split keeps the unsplit rest on the right, rsplit on 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.
  • sep is literal, not a regular expression. Use re.split() for patterns.
  • Both parameters can be keywords (rsplit(sep=",", maxsplit=1)).
  • Also on bytes and bytearray.