str.rsplit()
The rsplit() method splits a string from the right side into a list of substrings. It’s identical to split() except that it begins splitting from the right side of the string rather than the left.
Signature
str.rsplit(sep=None, maxsplit=-1)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
sep | str | None | The delimiter to split on. If None, splits on any whitespace. |
maxsplit | int | -1 | Maximum number of splits. -1 means no limit. |
Return Value
Returns a list of strings. The substrings do not include the separator.
Basic Examples
# Split from the right
text = "one,two,three"
text.rsplit(",")
# Result: ['one', 'two', 'three']
# With maxsplit
text.rsplit(",", 1)
# Result: ['one,two', 'three']
# Splitting on whitespace
"hello world python".rsplit()
# Result: ['hello', 'world', 'python']
How It Differs from split()
The key difference is apparent when maxsplit is specified:
text = "a,b,c,d"
# split() starts from the left
text.split(",", 1)
# Result: ['a', 'b,c,d']
# rsplit() starts from the right
text.rsplit(",", 1)
# Result: ['a,b', 'c,d']
This behavior matters when you need to split off a specific number of elements from the end of a string.
Common Use Cases
Splitting a filename
filename = "document.final draft.pdf"
name, ext = filename.rsplit(".", 1)
# name = 'document.final draft', ext = 'pdf'
Parsing reversed data
When processing data where the rightmost element is the most significant:
path = "/home/user/documents/file.txt"
parts = path.rsplit("/", 1)
# parts = ['/home/user/documents', 'file.txt']
Behavior Details
When sep is None, rsplit() treats consecutive whitespace as a single separator and removes empty strings from the result:
# Multiple spaces are treated as one separator
"a b c".rsplit()
# Result: ['a', 'b', 'c']
# Leading and trailing whitespace is removed
" hello world ".rsplit()
# Result: ['hello', 'world']
When a separator is provided, the string splits only on that exact substring:
# Split on double hyphen
"foo--bar--baz".rsplit("--")
# Result: ['foo', 'bar', 'baz']
# Consecutive separators produce empty strings
"a::b::".rsplit("::")
# Result: ['a', 'b', '']
The maxsplit argument controls how many splits occur. A value of 0 returns the original string in a list:
"one,two,three".rsplit(",", 0)
# Result: ['one,two,three']