Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readPython
#Python strings#string methods#rpartition#partition
Illustration of Python string rpartition splitting a string at the last occurrence of a separator.

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.

python
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.

MethodSplits atTypical use case
partitionFirst occurrenceParsing headers, first key-value pair
rpartitionLast occurrenceFile extension, last path component

For example, getting the last path segment of a URL:

python
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.

python
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.

python
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.

python
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.

python
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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.