Python
String Manipulation
String Splitting
Delimiter
Programming

Splitting on last delimiter in Python string?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python's str.rsplit() method splits a string from the right, making it the direct solution for splitting on the last occurrence of a delimiter. With maxsplit=1, it splits only on the last delimiter, producing two parts. The companion method str.rpartition() always returns three parts (before, delimiter, after) and never raises an error. Both are more readable and reliable than manual approaches using rfind().

rsplit() with maxsplit=1

python
1text = "path/to/my/file.txt"
2
3# Split on the LAST "/"
4parts = text.rsplit("/", maxsplit=1)
5print(parts)  # ['path/to/my', 'file.txt']
6
7# Compare with regular split on the FIRST "/"
8parts = text.split("/", maxsplit=1)
9print(parts)  # ['path', 'to/my/file.txt']

rsplit() works identically to split() except it starts splitting from the right side of the string.

rpartition()

rpartition() always returns a 3-tuple: (before, separator, after):

python
1text = "name.first.last"
2
3before, sep, after = text.rpartition(".")
4print(before)  # "name.first"
5print(sep)     # "."
6print(after)   # "last"

If the delimiter is not found, rpartition() returns ('', '', original_string):

python
1text = "no_dots_here"
2before, sep, after = text.rpartition(".")
3print(before)  # ""
4print(sep)     # ""
5print(after)   # "no_dots_here"

This makes it safe to use without checking whether the delimiter exists.

Practical Examples

Splitting File Extension

python
1filename = "archive.tar.gz"
2
3# Get name and final extension
4name, _, ext = filename.rpartition(".")
5print(name)  # "archive.tar"
6print(ext)   # "gz"
7
8# Compare: os.path.splitext splits on first dot from the right
9import os
10name, ext = os.path.splitext(filename)
11print(name)  # "archive.tar"
12print(ext)   # ".gz" (includes the dot)

Splitting Domain from URL Path

python
1url = "https://example.com/api/v2/users"
2
3# Split on last "/"
4base, _, resource = url.rpartition("/")
5print(base)      # "https://example.com/api/v2"
6print(resource)  # "users"

Splitting Package from Class Name

python
1qualified_name = "com.example.myapp.services.UserService"
2
3package, _, class_name = qualified_name.rpartition(".")
4print(package)     # "com.example.myapp.services"
5print(class_name)  # "UserService"

Splitting on Multi-Character Delimiter

python
1log_line = "2025-01-15 :: INFO :: Server started :: Port 8080"
2
3# Split on last " :: "
4before, _, after = log_line.rpartition(" :: ")
5print(before)  # "2025-01-15 :: INFO :: Server started"
6print(after)   # "Port 8080"

rsplit() vs rpartition()

python
1text = "a.b.c.d"
2
3# rsplit returns a list, can split multiple times
4text.rsplit(".", maxsplit=1)   # ['a.b.c', 'd']
5text.rsplit(".", maxsplit=2)   # ['a.b', 'c', 'd']
6text.rsplit(".")               # ['a', 'b', 'c', 'd']
7
8# rpartition always returns exactly 3 parts
9text.rpartition(".")           # ('a.b.c', '.', 'd')
Featurersplit(sep, 1)rpartition(sep)
Return typeList of 2 elementsTuple of 3 elements
Delimiter in resultNoYes (middle element)
Delimiter not foundReturns [original]Returns ('', '', original)
Multiple splitsYes (adjust maxsplit)No (always one split)

Using rfind() Manually

python
1text = "hello-world-python"
2
3# Find the last occurrence of "-"
4idx = text.rfind("-")
5
6if idx != -1:
7    before = text[:idx]
8    after = text[idx + 1:]
9    print(before)  # "hello-world"
10    print(after)   # "python"

This works but is verbose compared to rsplit() or rpartition(). Use it only when you need the index position itself.

split() vs rsplit() Comparison

python
1text = "one:two:three:four"
2
3# split from left
4text.split(":", maxsplit=1)   # ['one', 'two:three:four']
5text.split(":", maxsplit=2)   # ['one', 'two', 'three:four']
6
7# split from right
8text.rsplit(":", maxsplit=1)  # ['one:two:three', 'four']
9text.rsplit(":", maxsplit=2)  # ['one:two', 'three', 'four']
10
11# Without maxsplit, both return the same result
12text.split(":")   # ['one', 'two', 'three', 'four']
13text.rsplit(":")  # ['one', 'two', 'three', 'four']

The difference only matters when maxsplit limits the number of splits.

Edge Cases

python
1# Delimiter at the end
2"hello.".rsplit(".", maxsplit=1)     # ['hello', '']
3"hello.".rpartition(".")            # ('hello', '.', '')
4
5# Delimiter at the start
6".hello".rsplit(".", maxsplit=1)     # ['', 'hello']
7".hello".rpartition(".")            # ('', '.', 'hello')
8
9# Multiple consecutive delimiters
10"a..b".rsplit(".", maxsplit=1)       # ['a.', 'b']
11
12# Empty string
13"".rsplit(".", maxsplit=1)           # ['']
14"".rpartition(".")                   # ('', '', '')
15
16# No delimiter found
17"hello".rsplit(".", maxsplit=1)      # ['hello']
18"hello".rpartition(".")             # ('', '', 'hello')

Common Pitfalls

  • Forgetting maxsplit=1: rsplit(".") without maxsplit splits on ALL dots, same as split("."). Add maxsplit=1 to split only on the last occurrence.
  • Unpacking rsplit when delimiter is missing: a, b = "nodot".rsplit(".", 1) raises ValueError because the result is ['nodot'] (one element, not two). Check the length first or use rpartition() which always returns three values.
  • Using split instead of rsplit: "a.b.c".split(".", 1) gives ['a', 'b.c'] (splits on first dot). rsplit(".", 1) gives ['a.b', 'c'] (splits on last dot). Choose based on which part you want to keep intact.
  • os.path.splitext for file extensions: For file paths, os.path.splitext() is more correct than rsplit(".") because it handles edge cases like dotfiles (.bashrc) and no-extension files.
  • rpartition includes the delimiter: Unlike rsplit, rpartition returns the delimiter as the middle element. If you do not need it, use _ to discard: before, _, after = text.rpartition(".").

Summary

  • Use str.rsplit(delimiter, maxsplit=1) to split on the last occurrence of a delimiter
  • Use str.rpartition(delimiter) for a safe split that always returns 3 parts
  • rsplit without maxsplit is the same as split — always specify maxsplit=1 for "last delimiter" behavior
  • rpartition is safer for unpacking because it never changes the number of return values
  • Use os.path.splitext() for file extension splitting instead of manual string splitting

Course illustration
Course illustration

All Rights Reserved.