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.
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
| Parameter | What it is |
|---|---|
sepoptional, default None | The text to cut at. With None, any run of whitespace counts and empty pieces are dropped. |
maxsplitoptional, 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
text = "a.b.c"
print(text.split(".", 1))
print(text.rsplit(".", 1))['a', 'b.c'] ['a.b', 'c']
2File name and folder from a path
path = "/home/ana/docs/report.pdf"
folder, filename = path.rsplit("/", 1)
print(folder)
print(filename)/home/ana/docs report.pdf
3Separate the last name
full = "Maria da Silva"
first, last = full.rsplit(" ", 1)
print(first)
print(last)Maria da Silva
4Remove any file extension
for name in ["photo.jpg", "backup.tar.gz", "README"]:
print(name.rsplit(".", 1)[0])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()
line = "red green blue"
print(line.split() == line.rsplit())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.
parts = "1-2-3".rsplit("-")
print(parts)
print(parts[::-1])['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.