🕯️ Magic Note
When called with no arguments, split() divides the string at any whitespace: spaces, tabs, newlines. It then returns a list of substrings. Multiple consecutive whitespace characters are treated as a single separator, and empty strings are never returned.
- Without arguments splits on any whitespace: spaces, tabs, newlines
- With a custom separator, pass it as an argument like .split(“,”)
- Returns a list of strings
- Empty strings produce [“”], not an empty list
Use .split(“,”) for CSV data or custom delimiters.
Use .split(maxsplit=1) to split only the first occurrence.
For splitting lines of text, consider .splitlines() which handles different newline characters more gracefully.
| Input String | split() Call | Output |
|---|---|---|
| “hi again” | .split() | [“hi”, “again”] |
| “one two three” | .split() | [“one”, “two”, “three”] |
| “a,b,c,d” | .split(“,”) | [“a”, “b”, “c”, “d”] |
| “hello world” | .split() | [“hello”, “world”] |
| “apple-banana-cherry” | .split(“-“) | [“apple”, “banana”, “cherry”] |
Python
# Basic word splitting
sentence = “code coffee conjure”
words = sentence.split()
print(words)
# Output: [“code”, “coffee”, “conjure”]
Python
# Using a custom separator
data = “name:age:city”
parts = data.split(“:”)
print(parts)
# Output: [“name”, “age”, “city”]
Python
# Limiting number of splits
text = “one two three four”
first_only = text.split(maxsplit=1)
print(first_only)
# Output: [“one”, “two three four”]
- Confusing .split() (splits on any whitespace) with .split(” “) (splits on spaces only)
- Expecting .split() to modify the original string, it returns a new list and leaves the string unchanged
- Using .split() on extremely large strings without considering memory usage, the resulting list can be very large
⚡ Whisper
A stream of words flows together. The split cuts gently at every space. Each piece is freed. Each whisper becomes a word standing alone. Together they were one. Apart they are many.