rsplit() splits a string just like split(), but it starts from the right. It returns a list of strings, and the separator is not kept.
Without maxsplit the result is exactly the same as split(). The difference appears when you limit the cuts: rsplit() makes them at the last separators, so "a-b-c".rsplit("-", 1) is ['a-b', 'c']. That is handy for file extensions and for the last part of an address.
text.rsplit() 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 a separator and an optional limit. With no arguments it splits on whitespace.
python
parts = text.rsplit()
parts = text.rsplit(sep)
parts = text.rsplit(sep, maxsplit)
Call
What it does
"a b c".rsplit()
Returns ['a', 'b', 'c']. With no limit it works like split().
"2024-05-01".rsplit("-", 1)
Returns ['2024-05', '01']. Only the last hyphen is used for a cut.
"one two three".rsplit(None, 1)
Returns ['one two', 'three']. None means whitespace, and the single cut is made at the last space.
To cut from the left use split(). To cut once at the last separator and keep it, use rpartition().
Library declarations
python
str.rsplit(sep=None, maxsplit=-1) -> list
# returns: a list of strings
# raises: ValueError if sep is an empty string
Parameters
Parameter
Description
sep
Optional. The text to split at. If it is omitted or None, the string is split on runs of whitespace. An empty string raises ValueError.
maxsplit
Optional. The most cuts to make, counted from the right. Default -1, which means no limit.
Return Value
Return Value
Description
list
A list of strings, in the same left-to-right order as the original text. The original string is not changed.
Python Examples
Example 1 — Left Cuts and Right Cuts
Split the same text with split() and rsplit(), with and without a limit.
python
text = "a-b-c-d"
print(text.split("-", 1))
print(text.rsplit("-", 1))
print(text.rsplit("-", 2))
print(text.rsplit("-"))