Sub topic 4
Limiting splits with maxsplit and rsplit
This chapter assumes you know how str.split works with a separator and with no argument, and that you are comfortable with lists, tuples and unpacking. Here you will cap the number of splits and split from the right instead of the left.
Why limit the number of splits
Plain split cuts at every separator. Sometimes only the first or last separator is meaningful, and the rest of the text is data that happens to contain the same character. A line such as key=value=more should become a key and a value, where the value is value=more.
The second argument to split is maxsplit. It is the maximum number of cuts, so the result has at most maxsplit + 1 items.
print("key=value=more".split("=", 1)) # ['key', 'value=more']
print("a/b/c/d".rsplit("/", 1)) # ['a/b/c', 'd']The first call stops after one cut, so everything after the first = stays together. The second call is rsplit, covered below.
How maxsplit counts
maxsplit counts cuts, not pieces. A value of 1 gives two pieces, and 2 gives three.
text = "a:b:c:d"
print(text.split(":", 0)) # ['a:b:c:d']
print(text.split(":", 1)) # ['a', 'b:c:d']
print(text.split(":", 2)) # ['a', 'b', 'c:d']
print(text.split(":", -1)) # ['a', 'b', 'c', 'd']A maxsplit of 0 performs no splitting and returns the whole string in a one-item list. A negative value, which is also the default, means no limit. You can pass it by keyword as well: text.split(":", maxsplit=1). With a keyword, the separator can be given as sep=":".
Splitting from the right with rsplit
rsplit takes the same arguments as split but makes its cuts starting at the right end. Without a maxsplit, the result is identical to split. The difference appears only when the limit is smaller than the number of separators.
path = "reports/2026/q3/summary.txt"
print(path.split("/", 1)) # ['reports', '2026/q3/summary.txt']
print(path.rsplit("/", 1)) # ['reports/2026/q3', 'summary.txt']Both calls make one cut. split finds the first /, and rsplit finds the last one. The order of items in the result list is the same as the order in the original string, so the final piece of rsplit is still last.
Unpacking the result
When you know how many pieces a limited split produces, you can unpack it straight into variables. This is a common way to read name=value lines or to separate a file name from its directory.
line = "timeout=30=seconds"
key, value = line.split("=", 1)
print(key) # timeout
print(value) # 30=seconds
directory, filename = "a/b/c/d".rsplit("/", 1)
print(directory) # a/b/c
print(filename) # dCommon errors
The limit only guarantees an upper bound. If the separator is missing, you get fewer pieces than you expect, and unpacking fails.
parts = "no-equals-sign".split("=", 1)
print(parts) # ['no-equals-sign']
try:
key, value = "no-equals-sign".split("=", 1)
except ValueError as error:
print(error) # not enough values to unpack (expected 2, got 1)Handle this by checking len(parts), catching ValueError, or using partition, which always returns three items. The next chapters cover partition.
Other frequent mistakes:
- Expecting
maxsplit=2to return two items. It returns up to three. - Using
splitwhen the last separator matters. For file names and extensions,rsplit(".", 1)is correct, andsplit(".", 1)is not. - Forgetting that the whitespace form also accepts a limit.
"a b c d".split(None, 1)gives['a', 'b c d']. The remainder keeps its inner spacing, but leading whitespace of the remainder is removed.
print("a b c d".split(None, 1)) # ['a', 'b c d']
print("a b c d".rsplit(None, 1)) # ['a b c', 'd']Pass None as the separator to get whitespace splitting together with a limit.
Summary of the options
| Call | Meaning | Result for `"a-b-c"` |
|---|---|---|
| `split("-")` | Cut at every separator | `['a', 'b', 'c']` |
| `split("-", 1)` | One cut from the left | `['a', 'b-c']` |
| `rsplit("-", 1)` | One cut from the right | `['a-b', 'c']` |
| `split("-", 0)` | No cuts | `['a-b-c']` |
Exercise
A log line is "ERROR:db:connection lost: retry in 5s". Using one split call with a limit, how do you get the level "ERROR" and the rest of the message "db:connection lost: retry in 5s" into two variables? How would you instead separate only the final part after the last colon?
Show answer
Use level, message = line.split(":", 1) to cut at the first colon only. This gives 'ERROR' and 'db:connection lost: retry in 5s'. To separate the final part, use head, tail = line.rsplit(":", 1), which cuts at the last colon and gives 'ERROR:db:connection lost' and ' retry in 5s'.
Exercise
What does "a,b,c,d".split(",", 2) return, and how many items does it have?
Show answer
It returns ['a', 'b', 'c,d']. There are 3 items, because maxsplit=2 allows two cuts and produces at most maxsplit + 1 pieces.