Sub topic 3
Splitting on whitespace with split()
This chapter assumes you can run Python code, know how strings and lists work, and can call methods and read their return values. It covers what split() does when you give it no argument, and how that differs from split(" ").
Two calls that look alike
Calling str.split with no argument is a separate mode, not a shortcut for split(" "). Without an argument, Python treats any run of whitespace as one separator. It also ignores whitespace at the start and end of the string.
line = " hello world \n"
print(line.split()) # ['hello', 'world']
print(line.split(" ")) # ['', '', 'hello', '', '', 'world', '\n']split(" ") splits on every single space character. Two spaces in a row have an empty string between them, so you get empty strings. The newline at the end is not a space, so it stays attached to the last piece.
split() never returns empty strings. The empty string at the start of the split(" ") result came from the leading spaces. split() skips them.
What counts as whitespace
With no argument, split() treats these as whitespace:
- spaces
- tabs (
\t) - newlines (
\n) and carriage returns (\r) - other whitespace characters, including the non-breaking space and other Unicode spaces
This is why split() is a good default for text typed or pasted by people. You don't need to know whether the gaps are one space, three spaces or a tab.
messy = "name\tage city\n"
print(messy.split()) # ['name', 'age', 'city']Empty and blank input
The two modes also differ on empty input. An explicit separator keeps the one empty field. split() has nothing to return.
print("".split(",")) # ['']
print("".split()) # []
print(" \n".split()) # []
print(" ".split(" ")) # ['', '', '', '']A string of only whitespace gives an empty list with split(). That makes it easy to test for blank input:
def word_count(text):
return len(text.split())
print(word_count("one two three")) # 3
print(word_count(" ")) # 0Compare this with len("".split(",")), which is 1 for an empty string. If you count fields with an explicit separator, handle empty input yourself.
Choosing between the two
The deciding question is whether an empty field has meaning in your data.
| Situation | Use | Why |
|---|---|---|
| Words in free text | `split()` | Extra spaces and tabs don't create fake words |
| Columns padded with spaces | `split()` | Alignment padding varies in width |
| Fields where an empty value is real, such as `a,,c` | `split(",")` | Position matters, so empty fields must stay |
| Fixed single-space format | `split(" ")` | You want each space to count |
Common mistakes
- Using
split(" ")on user input. Double spaces, trailing newlines and tabs all leak into the result. Switch tosplit(). - Using
split()on delimited data with empty fields. In"a,,c"the middle field is empty on purpose. Splitting on whitespace would hide that. - Passing
Noneand expecting something different.split(None)is the same assplit(). PassingNoneas the first argument is how you setmaxsplitwhile keeping whitespace mode, which the next chapter covers. - Forgetting that strings are immutable.
line.split()returns a new list. It does not changeline.
line = " a b "
line.split()
print(line) # ' a b ' (unchanged)
parts = line.split()
print(parts) # ['a', 'b']How the two modes compare
Exercise
What does each call return for the string s = " a\tb c\n"? (1) s.split() (2) s.split(" ")
Show answer
(1) ['a', 'b', 'c']. With no argument, tabs, runs of spaces and the trailing newline all count as whitespace separators, and the edges are trimmed. (2) ['', 'a\tb', '', 'c\n']. Only single space characters separate pieces, so the leading space gives an empty string, the tab stays inside 'a\tb', the double space gives another empty string, and the newline stays attached to 'c\n'.
Exercise
A function must return True if a string contains no words, even if it holds spaces, tabs or newlines. Write it using split().
Show answer
def is_blank(text): return not text.split(). For blank input, split() returns an empty list, which is falsy, so not gives True. For " hi " it returns ['hi'], which is truthy, so the function gives False.