String method

str.rsplit()

Cuts a string into a list of pieces like split(), but when you limit the cuts with maxsplit it starts from the right end.

IntermediateEvery example below runs in your browser. Change the code and press Run.

str.rsplit(sep=None, maxsplit=-1)

rsplit() splits a string into a list, just like str.split(). Without maxsplit the two give exactly the same result.

The difference appears when you limit the number of cuts: rsplit() makes them from the right end, so the left part stays together. That is exactly what you want for the last word of a name, the file name at the end of a path, or the extension after the last dot.

The pieces still come back in normal left-to-right order; only the place of the cuts changes.

Parameters

ParameterWhat it is
sep
optional, default None
The text to cut at. With None, any run of whitespace counts and empty pieces are dropped.
maxsplit
optional, default -1
The most cuts to make, counting from the right. -1 means no limit.

Return value

A new list of strings.

Examples

1split() vs rsplit() with one cut

Pythoneditable
text = "a.b.c"
print(text.split(".", 1))
print(text.rsplit(".", 1))
Output
['a', 'b.c']
['a.b', 'c']

2File name and folder from a path

Pythoneditable
path = "/home/ana/docs/report.pdf"
folder, filename = path.rsplit("/", 1)
print(folder)
print(filename)
Output
/home/ana/docs
report.pdf

3Separate the last name

Pythoneditable
full = "Maria da Silva"
first, last = full.rsplit(" ", 1)
print(first)
print(last)
Output
Maria da
Silva

4Remove any file extension

Pythoneditable
for name in ["photo.jpg", "backup.tar.gz", "README"]:
    print(name.rsplit(".", 1)[0])
Output
photo
backup.tar
README

When there is no dot, the list has one item: the whole name.

5Without maxsplit it is the same as split()

Pythoneditable
line = "red green blue"
print(line.split() == line.rsplit())
Output
True

Common mistakes

Expecting the pieces in reverse order

rsplit() only cuts from the right; it does not reverse the list. Use [::-1] if you want the reverse.

Pythoneditable
parts = "1-2-3".rsplit("-")
print(parts)
print(parts[::-1])
Output
['1', '2', '3']
['3', '2', '1']

Questions people ask

When should I use rsplit() instead of split()?

When you set maxsplit and the part you want is at the right end: an extension, a last name, a file name.

How do I get the text after the last dot?

text.rsplit(".", 1)[-1], or text.rpartition(".")[2].

Is there a better tool for file paths?

Yes: pathlib.Path(path).name and .suffix handle the details of real paths.

Spotted a mistake on this page? Tell us