Sub topic 3
Splitting on whitespace with split()
This chapter assumes you can run Python code, work with strings and lists, call methods and read their return values, and write simple for loops. It covers what str.split() does when you give it no separator, and why that differs from split(" ").
Two methods with one name
str.split has two modes, chosen by the first argument.
text.split(sep)cuts at every occurrence of the exact separatorsep. Empty fields are kept.text.split()(ortext.split(None)) cuts at runs of whitespace. Empty fields never appear.
The second mode is not just a shortcut for split(" "). It follows different rules, shown below.
line = " hello world \n"
print(line.split()) # ['hello', 'world']
print(line.split(" ")) # ['', '', 'hello', '', '', 'world', '\n']line.split(" ") produced seven items. Each space is a separator, so two leading spaces give two empty strings, and the three spaces between the words give two more. The last item is '\n', because the newline is not a space.
line.split() treats any run of whitespace as one separator and discards whitespace at both ends. The result has only the words.
text = "a,b,,c"
print(text.split(",")) # ['a', 'b', '', 'c']Compare this with the explicit-separator mode from the previous chapter. With "," the empty field between the two commas is real data. With no argument, there is no such thing as an empty field.
The rules of whitespace splitting
The no-argument mode follows four rules:
- A run of one or more whitespace characters is a single separator.
- Leading whitespace is ignored.
- Trailing whitespace is ignored.
- The result never contains empty strings.
The table shows how the two modes differ on common inputs.
| Input | `split()` | `split(" ")` |
|---|---|---|
| `""` | `[]` | `['']` |
| `" "` (three spaces) | `[]` | `['', '', '', '']` |
| `"a b"` | `['a', 'b']` | `['a', 'b']` |
| `"a b"` | `['a', 'b']` | `['a', '', 'b']` |
| `" a"` | `['a']` | `['', 'a']` |
| `"a\tb"` | `['a', 'b']` | `['a\tb']` |
The last row matters in practice. A tab is whitespace, so split() cuts there. A tab is not a space, so split(" ") does not.
What counts as whitespace
For str, whitespace means any character for which str.isspace() is true. That is more than the space character:
- space, tab (
\t), newline (\n), carriage return (\r) - vertical tab (
\x0b) and form feed (\x0c) - Unicode spaces such as the non-breaking space (
\u00a0) and the em space (\u2003)
text = "a\tb\nc\r\nd\x0be\x0cf\u00a0g\u2003h"
print(text.split()) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
# A zero-width space is not whitespace, so nothing is split here.
print(len("a\u200bb".split())) # 1The \r\n pair in the example is two whitespace characters in a row, so it counts as one separator.
Non-breaking spaces often appear in text copied from web pages and word processors. split() handles them, while split(" ") does not. Zero-width characters are a different problem. They are invisible and are not whitespace, so split() leaves them inside the words.
Empty and whitespace-only input
Because rule 4 forbids empty strings, an input with no words yields an empty list:
print("".split()) # []
print(" \n\t ".split()) # []
print("".split(",")) # ['']
print("".split(" ")) # ['']This difference affects control flow. After fields = line.split(), the test if not fields: reliably detects a blank or whitespace-only line. After line.split(","), the result always has at least one item, so if not fields never fires. You would need to check the original string.
def first_word(line):
fields = line.split()
if not fields:
return None
return fields[0]
print(first_word(" ")) # None
print(first_word(" run tests ")) # runCombining with maxsplit
The no-argument mode accepts a limit. Pass None as the separator, or use keywords:
s = " a b c "
print(s.split(None, 1)) # ['a', 'b c ']
print(s.split(maxsplit=1)) # ['a', 'b c ']
print(s.rsplit(None, 1)) # [' a b', 'c']Leading whitespace is skipped before the first word. After the allowed number of cuts, the remainder is returned as one item. The remainder keeps its internal spacing and its trailing whitespace. The rsplit call works from the right and keeps the leading whitespace of the remainder.
This pattern is useful for a "command followed by free text" format:
line = "say hello to everyone "
command, message = line.split(None, 1)
print(command) # say
print(repr(message)) # 'hello to everyone 'You will usually want message.strip() as well. If the line contains only the command, split(None, 1) returns a one-item list and the unpacking raises ValueError.
Unpacking the result
split() pairs naturally with tuple unpacking, which checks the field count for you.
line = "GET /index.html 200 512\n"
method, path, status, size = line.split()
print(method, path, int(status), int(size)) # GET /index.html 200 512
try:
method, path = "GET /a /b".split()
except ValueError as exc:
print(exc) # too many values to unpack (expected 2)Here split() also removed the trailing newline, so you do not need a separate strip(). Because of the extra spaces after GET, split(" ") would have produced a list with the wrong number of items and made this line fail.
When the number of fields varies, use starred unpacking:
command, *args = "git commit -m fix".split()
print(command) # git
print(args) # ['commit', '-m', 'fix']Common uses
Reading files line by line
Each line from a file ends with '\n'. Whitespace splitting absorbs it:
import io
data = io.StringIO("alice 30\nbob 25\n\ncarol 41\n")
for line in data:
fields = line.split()
if not fields:
continue # skip blank lines
name, age = fields
print(name, int(age))This prints alice 30, bob 25 and carol 41. The io.StringIO object stands in for an open file so the example runs as written.
Counting words
from collections import Counter
text = "the cat and the hat. The end"
counts = Counter(text.lower().split())
print(counts["the"]) # 3
print(counts["hat."]) # 1The count for "hat." shows the limit of this approach. split() cuts only at whitespace, so punctuation stays attached to the words. For real text analysis, strip punctuation first or use re.findall, which a later chapter covers.
Normalising whitespace
Splitting and then joining with a single space collapses every run of whitespace, including newlines and tabs, and trims the ends:
messy = " too many\n\tspaces "
print(" ".join(messy.split())) # too many spacesThis is a lossy operation. The original spacing cannot be recovered from the result.
When not to use split()
Whitespace splitting is the wrong tool whenever empty fields carry meaning. In a tab-separated file with a missing value, collapsing the separators shifts every later column:
row = "id\t\tname" # the middle field is empty
print(row.split()) # ['id', 'name']
print(row.split("\t")) # ['id', '', 'name']Use split("\t") for that row, because the position of each field matters. The same applies to any format that uses a visible separator such as , or |.
Whitespace splitting is also wrong when fields can contain spaces, such as names like "Mary Ann", unless you use maxsplit to protect the last field.
The flowchart summarises the choice.
Common errors
- Using
split(" ")on user input. Double spaces, trailing newlines and tabs produce empty strings and glued words. Prefersplit()unless you need to preserve empty fields. - Expecting an empty list from
"".split(","). It returns['']. Only the no-argument mode returns[]. - Forgetting the result is a new list. Strings are immutable, so
line.split()does not changeline. If you ignore the return value, nothing happens. - Assuming a fixed field count. Unpack inside a
tryblock, or checklen(fields)when the input comes from outside your program. - Passing a whitespace string as the separator.
split(" ")with two spaces is an exact separator, not a "whitespace" setting. OnlyNone(or no argument) selects whitespace mode.
Exercise
What do " x y ".split(None, 1) and " x y ".rsplit(None, 1) return?
Show answer
The first returns ['x', 'y ']. Leading whitespace is skipped, one cut is made after x, and the remainder 'y ' keeps its trailing space. The second returns [' x', 'y']. Trailing whitespace is skipped, one cut is made before y, and the remainder ' x' keeps its leading spaces.
Exercise
A line looks like " deploy prod --force ". Write one expression that gives the command deploy and a list of the remaining arguments, and say what happens if the line is blank.
Show answer
Use command, *args = line.split(). For the example line, command is 'deploy' and args is ['prod', '--force']. If the line is blank, line.split() returns [], so the unpacking raises ValueError because there are not enough values. Check if not fields: first, or catch the error.
Exercise
Why does "a\tb".split(" ") return ['a\tb'], while "a\tb".split() returns ['a', 'b']?
Show answer
split(" ") cuts only at the space character, and a tab is a different character, so no cut is made. split() with no argument cuts at any whitespace character, and a tab is whitespace.