Sub topic 4
Limiting splits with maxsplit and rsplit
This chapter assumes you can run Python code, know that strings and lists are sequences, and have used str.split with a separator and with no argument. Here you learn how to stop splitting after a fixed number of cuts, and how to make those cuts from the right-hand end of the string.
The maxsplit parameter
Both str.split and str.rsplit have the signature (sep=None, maxsplit=-1). The maxsplit argument is the largest number of cuts Python may make. Because each cut produces one more piece, the result holds at most maxsplit + 1 items.
print("key=value=more".split("=", 1)) # ['key', 'value=more']
print("a/b/c/d".split("/", 2)) # ['a', 'b', 'c/d']
print("a/b/c/d".split("/", 10)) # ['a', 'b', 'c', 'd']The last piece is not split. It is the untouched remainder of the string, and it can still contain the separator. Asking for more splits than the string has separators is not an error. Python makes as many cuts as it can.
You can pass maxsplit by position or by keyword. The keyword form is the only way to use it together with the default whitespace splitting, unless you write None as the separator:
text = "alpha beta gamma"
print(text.split(maxsplit=1)) # ['alpha', 'beta gamma']
print(text.split(None, 1)) # ['alpha', 'beta gamma']Prefer the keyword form. split(None, 1) makes the reader work out what None means.
Special values
| Call on `"a/b/c/d"` | Result | Why |
|---|---|---|
| `split("/")` | `['a', 'b', 'c', 'd']` | The default of -1 means no limit |
| `split("/", -1)` | `['a', 'b', 'c', 'd']` | Any negative value means no limit |
| `split("/", 0)` | `['a/b/c/d']` | Zero cuts, so the whole string comes back in a list |
| `split("/", 1)` | `['a', 'b/c/d']` | One cut, at the first separator |
| `split("/", 2)` | `['a', 'b', 'c/d']` | Two cuts from the left |
| `rsplit("/", 1)` | `['a/b/c', 'd']` | One cut, at the last separator |
| `rsplit("/", 2)` | `['a/b', 'c', 'd']` | Two cuts from the right |
A frequent mistake is to read maxsplit as the number of items wanted. split(",", 2) returns up to three items, not two. If you want N items, pass N - 1.
Splitting from the right with rsplit
rsplit makes its cuts starting at the right end. The pieces are still returned in left-to-right order, so you read the result the same way as with split.
path = "a/b/c/d"
print(path.split("/", 1)) # ['a', 'b/c/d']
print(path.rsplit("/", 1)) # ['a/b/c', 'd']Without a limit, split and rsplit give identical results, because every separator is cut either way. The two methods differ only when maxsplit stops the process early. That makes rsplit the natural choice when the part you want is at the end and the front part may contain the separator:
print("archive.tar.gz".rsplit(".", 1)) # ['archive.tar', 'gz']
print("2001:db8::1:8080".rsplit(":", 1)) # ['2001:db8::1', '8080']In both examples a left-to-right split would cut at the wrong place. The host in the second example contains colons itself.
maxsplit with whitespace splitting
With no separator, split treats a run of whitespace as one separator and ignores whitespace at the start. maxsplit keeps those rules, but it changes what happens to the remainder.
line = " one two three four \n"
print(line.split(maxsplit=2))
# ['one', 'two', 'three four \n']Python skips the leading whitespace, cuts after one and two, and then stops. The final item is everything that is left, with its internal spacing, trailing space and newline unchanged. If you need the remainder cleaned up, call strip() on it yourself.
rsplit mirrors this at the other end:
print(line.rsplit(maxsplit=2))
# [' one two', 'three', 'four']Here the leading text stays as the unsplit remainder, including its leading spaces. The trailing whitespace is dropped.
With maxsplit=0 and no separator, you get the string with the outer whitespace removed on the side that would have been cut:
print(" a b ".split(None, 0)) # ['a b ']
print(" a b ".rsplit(None, 0)) # [' a b']You will seldom want this, but it shows that whitespace splitting is not the same as a plain strip().
Empty fields and a limit
When you give an explicit separator, empty fields are kept, exactly as in an unlimited split. The limit counts every cut, including cuts that produce an empty string.
print("a,,b".split(",", 1)) # ['a', ',b']
print("a,b,".split(",", 1)) # ['a', 'b,']
print("a,b,".rsplit(",", 1)) # ['a,b', '']The last line is a useful edge case. With a trailing separator, rsplit(",", 1) cuts at that last comma and returns an empty string as the final item. Check for this if the trailing separator is possible in your data.
An empty separator is not allowed. "abc".split("") raises ValueError: empty separator, with or without a limit.
Unpacking the result safely
The usual reason to set maxsplit is to unpack a known number of items:
name, value = "color=dark=blue".split("=", 1)
print(name) # color
print(value) # dark=blueThis works only when the separator occurs at least once. If it does not, the result has a single item and unpacking fails:
try:
name, value = "novalue".split("=", 1)
except ValueError as exc:
print(exc) # not enough values to unpack (expected 2, got 1)maxsplit guarantees an upper bound on the length, never a lower one. For a limit of 1, you have three common options:
- Wrap the unpacking in
tryandexcept ValueError, as above. - Check the length of the result before using it.
- Use
partition, which always returns three items. The next chapter covers it.
For larger limits, starred unpacking helps when the number of leading items is fixed and the rest varies:
first, *rest = "a b c d".split(" ", 1)
print(first) # a
print(rest) # ['b c d']This does not remove the failure case for the fixed items. "".split(" ", 1) returns [''], so first is empty and rest is an empty list. You still need to decide what an empty or malformed line means.
A worked example: parsing log lines
Log lines often have a few fixed fields followed by free text that contains the same separator. A limit keeps the message in one piece.
def parse_log_line(line):
"""Split 'DATE TIME LEVEL message...' into a dictionary."""
parts = line.rstrip("\n").split(" ", 3)
if len(parts) != 4:
raise ValueError(f"malformed log line: {line!r}")
date, time, level, message = parts
return {"date": date, "time": time, "level": level, "message": message}
entry = parse_log_line("2026-11-26 10:53:05 ERROR disk full: /dev/sda1\n")
print(entry["level"]) # ERROR
print(entry["message"]) # disk full: /dev/sda1
try:
parse_log_line("2026-11-26 10:53:05 ERROR")
except ValueError as exc:
print(exc) # malformed log line: '2026-11-26 10:53:05 ERROR'Three points about this function:
split(" ", 3)gives at most four items, so the message may contain any number of spaces.- The length check turns a short line into a clear error. Without it, the unpacking would raise a less helpful message.
rstrip("\n")removes the line ending first. Without it, a line with exactly three fields and a trailing newline would end with'\n'in the last field.
Note that this version splits on a single space. If the fields can be separated by several spaces, use line.split(None, 3) instead, so that runs of whitespace count as one separator. The message then keeps its own internal spacing.
Choosing between split and rsplit
Decide by asking which end of the string has the part with a predictable structure.
- Use
split(sep, n)when the firstnfields are well-defined and the tail is free text. Examples are log lines,key=valuepairs where the value may contain=, and commands followed by arguments. - Use
rsplit(sep, n)when the last fields are well-defined and the head is free-form. Examples are file extensions,host:portpairs, and a name followed by a trailing number.
Common errors
- Off-by-one limit.
maxsplit=2gives up to three items. Count the pieces you want and subtract one. - Unpacking after a limit. The limit caps the length from above. Input without the separator still produces a shorter list.
- Expecting
rsplitto reverse the list. The items stay in their original left-to-right order. Only the choice of cut positions changes. - Forgetting the remainder is unprocessed. The last item of a limited
splitcan still hold separators, and for whitespace splitting it can hold leading and trailing spaces. - Passing the limit where the separator belongs.
"a b c".split(1)raisesTypeError, because the first argument must be a string orNone. Writesplit(maxsplit=1).
Exercise
What do "2026-11-26".split("-", 1) and "2026-11-26".rsplit("-", 1) return? Which one would you use to separate the day from the year-and-month part, and why?
Show answer
split("-", 1) returns ['2026', '11-26']. rsplit("-", 1) returns ['2026-11', '26']. To separate the day, use rsplit("-", 1), because it cuts at the last hyphen and leaves the year and month together in the first item.
Exercise
Write a function extension(name) that returns the part after the last dot of a file name, or an empty string if the name has no dot. Use rsplit with a limit. Then say what it returns for "report.final.pdf", "README" and ".bashrc".
Show answer
One solution:
def extension(name):
parts = name.rsplit(".", 1)
if len(parts) == 1:
return ""
return parts[1]
It returns 'pdf' for "report.final.pdf", '' for "README" because the result is a one-item list, and 'bashrc' for ".bashrc". The last result is questionable, since most tools treat .bashrc as a hidden file with no extension. That is why pathlib.Path(name).suffix is the better choice for real paths.
Exercise
The line " cmd arg one arg two\n" should become the command and the rest of the line as a single argument string. Which call do you use, and what does it return?
Show answer
Use line.split(maxsplit=1). It skips the leading whitespace, cuts once after cmd, and returns ['cmd', 'arg one arg two\n']. The remainder keeps its internal double space and the newline, so call .strip() on it if you need clean text.