Python String rpartition: Splitting at the Last Separator
python string rpartition: Learn how Python's str.rpartition() splits a string at the last occurrence of a separator, with syntax, examples, and edge cases.

The str.rpartition() method splits a string at the last occurrence of a given separator. It returns a three-element tuple: everything before the separator, the separator itself, and everything after it. This behavior is useful when you need to extract the final component of a path, the last path segment in a URL, or the final field in a log line without scanning the entire string manually.
How rpartition Works
str.rpartition(sep) searches the string from the end for the last occurrence of sep. The separator can be a multi-character string; passing an empty separator raises ValueError. When a separator is found, it returns a tuple (head, sep, tail), where head is the substring before the separator, sep is the separator itself, and tail is the substring after the separator. The separator is included in the output, which distinguishes this method from rsplit and split.
filename = "archive.tar.gz"
head, sep, tail = filename.rpartition(".")
print(head) # "archive.tar"
print(sep) # "."
print(tail) # "gz"The method always returns exactly three elements. If the separator appears multiple times, rpartition uses the last occurrence. This makes it useful for extracting file extensions, the last path segment in a URL, or the final field in a delimited record.
rpartition vs. partition: Choosing the Right Split
The partition method splits at the first occurrence of the separator, while rpartition splits at the last occurrence. The choice depends on which side of the string you care about.
| Method | Splits at | Typical use case |
|---|---|---|
partition | First occurrence | Parsing headers, first key-value pair |
rpartition | Last occurrence | File extension, last path component |
For example, getting the last path segment of a URL:
url = "https://example.com/path/page.html"
head, sep, tail = url.rpartition("/")
print(head) # "https://example.com/path"
print(tail) # "page.html"Using partition here would give head = "https:" and tail = "/example.com/path/page.html", which is rarely what you want when extracting the final segment. The choice is usually not about performance; both are linear-time searches. It is about which occurrence of the separator is semantically relevant.
Practical Examples: File Paths and Log Parsing
A common task is extracting the file extension from a path. rpartition handles this cleanly because the extension is always after the last dot.
def get_extension(filename):
_, sep, ext = filename.rpartition(".")
return ext if sep else ""
print(get_extension("report.pdf")) # "pdf"
print(get_extension("archive.tar.gz")) # "gz"
print(get_extension("README")) # ""The sep check matters when no dot is present: for a name like README, rpartition returns ("", "", "README"), so you must inspect sep rather than returning the whole filename.
In log parsing, you might need the last field of a comma-separated line. rpartition gives you the final value without splitting the entire line into a list.
log_line = "2025-01-15,INFO,user123,login success"
_, _, status = log_line.rpartition(",")
print(status) # "login success"These examples show that rpartition is not just a variant of partition; it is a precise tool for right-side extraction.
Handling Missing Separators: What rpartition Returns
When the separator is not found in the string, rpartition returns a tuple with two empty strings and the original string as the tail. This behavior is different from partition, which returns the original string as the head.
text = "hello world"
head, sep, tail = text.rpartition("x")
print(head) # ""
print(sep) # ""
print(tail) # "hello world"This asymmetry is important when you write code that assumes the separator exists. If you unpack the result directly, you must check whether sep is empty. A common pattern is to verify the separator before using the parts.
head, sep, tail = text.rpartition(".")
if sep:
# separator found
print(tail)
else:
# no separator, handle fallback
print(text)Ignoring this edge case can lead to subtle bugs, especially when the separator is a single character that might appear at the start or end of the string.
Performance and Memory Behavior of rpartition
rpartition scans the string from the end to find the last occurrence of the separator. This is an O(n) operation, where n is the length of the string. The scan can stop when the separator is found, so in the worst case it examines the entire string. The returned substrings are new string objects, so memory usage is proportional to the length of the head and tail. For large strings, this is similar to split or partition.
If you only need the part after the last separator, rpartition can be more direct than rsplit followed by indexing: rsplit(sep, 1) builds a one- or two-element list, while rpartition returns a tuple you can unpack directly.
Common Mistakes and Misconceptions
One frequent mistake is confusing rpartition with rsplit. rsplit splits the string into a list of substrings, while rpartition returns exactly three parts. Another error is assuming that rpartition always finds the separator. As shown earlier, it returns empty strings when the separator is absent.
Developers also sometimes assume that the last dot is always the extension boundary. For example.co.uk, rpartition(".") returns ("example.co", ".", "uk"); if you need co.uk, you need a different strategy, such as splitting on the second-to-last dot.
When to Use rpartition Over Other String Methods
Use rpartition when you need the last occurrence of a separator and you want the head, separator, and tail as separate values. It is the right choice for:
- Extracting file extensions
- Getting the last path component
- Parsing the final field of a delimited record
- Getting the last path segment of a URL
If you need all occurrences, use split. If you need the first occurrence, use partition. If you only need the tail and do not care about the head, rsplit(sep, 1)[-1] is an alternative, but rpartition is more explicit and avoids creating a list.
The method is part of the Python 3 string API and its behavior is consistent across supported versions. It is a small but useful tool that keeps string parsing code concise and intention-revealing.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.