Split on last occurrence of delimiter-Python
In Python, splitting strings according to a delimiter is a frequent task. What if, however, you only wish to split on the final instance of a delimiter? That’s where many beginners (and even some experienced coders) get stuck.
In this blog post, we’ll explore how to split a string on the last occurrence of a delimiter in Python, why it’s useful, and the best methods to do it efficiently.
Why Split on the Last Occurrence?
Sometimes, you don’t want to break a string every time a character appears — just on the last time it does. For example:
file_path = "/home/user/documents/report.pdf"
Here, if you want to get the filename only (report.pdf), you’d need to split based on /, but only the last slash matters.
Expected output:
['/home/user/documents', 'report.pdf']
Using rsplit() in Python
Python provides a built-in method called rsplit(), which is perfect for this use case.
Syntax:
str.rsplit(separator, maxsplit)
separator: The delimiter you want to split on
maxsplit: The maximum number of splits to do — from the right
Example:
file_path = "/home/user/documents/report.pdf" parts = file_path.rsplit("/", 1) print(parts)
Output:
['/home/user/documents', 'report.pdf']
This is the cleanest and most Pythonic way to split on the last occurrence of a delimiter.
Real-World Use Cases
Here are some common scenarios where splitting on the last occurrence is useful:
- Extracting file name from a file path
- Getting the domain from an email address
- Isolating the last word in a sentence
- Splitting key-value pairs where the delimiter might appear in the value
Example 1: Email Domain
email = "john.doe@example.co.uk"
username, domain = email.rsplit("@", 1)
print(domain) # Output: example.co.uk
Example 2: Last Word in a Sentence
sentence = "Python is easy to learn"
before_last, last_word = sentence.rsplit(" ", 1)
print(last_word) # Output: learn
Alternative: Using partition() and rpartition()
While rsplit() is more flexible, rpartition() is another great option when you want a fixed three-part split: before delimiter, delimiter itself, after delimiter.
Example:
text = "user@example.com"
before, delim, after = text.rpartition("@")
print(after) # Output: example.com
This is particularly useful if you always expect one occurrence and want both sides of the delimiter separately.
Which One Should You Use?
Method | Use Case |
---|---|
rsplit() | When you want a list of parts and control over max splits |
rpartition() | When you need just one split into three components |
Common Pitfalls to Avoid
Forgetting maxsplit=1: Without it, rsplit() behaves like regular split() but from the right.
Empty strings: If the delimiter isn’t found, you might not get the list format you expect.
Multiple delimiters: These methods work with a single specified delimiter — they won’t handle regex-like logic.
Tip:
Want to split on the last dot in a filename?
filename = "report.final.version.pdf"
name, ext = filename.rsplit(".", 1)
print(name) # Output: report.final.version
print(ext) # Output: pdf
difference between rsplit() and rpartition() in Python
Feature | rsplit() | rpartition() |
---|---|---|
Returns | A list of strings | A tuple of 3 parts |
Splitting | Splits from the right | Splits at the last occurrence only |
Max Splits | Can specify maxsplit (e.g., 1) | Always splits once |
Use Case | When you want to break into parts | When you need parts before/after a delimiter |
Example | "a-b-c".rsplit("-", 1) → ['a-b', 'c'] | "a-b-c".rpartition("-") → ('a-b', '-', 'c') |
Conclusion
In Python, splitting a string at the last occurrence of a delimiter is a common task, which can be done in just a few steps. By combining the rfind() method with string slicing, you can build a function for this purpose that really does its job well. This trick is useful whether you are dealing with file paths, URLs, or anything else joined by delimiters.
Please feel free to update the function provided according to your particular task and happy coding! Should any of you have questions or additional suggestions, please do drop a line in the comments.