Sub topic 2
Splitting on a separator with str.split
str.split(sep) cuts a string at every occurrence of a separator and returns the pieces as a list. It is the first tool most people reach for when they parse text. This chapter covers what it returns for ordinary input and for edge cases, and which mistakes come up in practice.
This chapter assumes you can run a script or the REPL, and that you know strings, lists and tuples, and how to call a method and read its return value. It also uses a basic for loop and a list comprehension. Whitespace splitting, maxsplit, splitlines and partition each have their own chapters, so this one only points to them.
Strings are immutable, so split returns a new list
A Python string cannot be changed after it is created. No string method edits the string it is called on. Each method builds a new value and returns it. split follows this rule: it leaves the original string alone and returns a new list of new str objects.
text = "a,b,c"
parts = text.split(",")
print(parts) # ['a', 'b', 'c']
print(text) # a,b,c (unchanged)Calling text.split(",") without storing the result does nothing useful. This is a common beginner bug. The list is created and then discarded, and text is the same as before.
The basic behaviour
With a separator, split scans the string from left to right. Each time it finds the separator, it ends the current piece and starts the next one. The separator itself is not included in any piece.
text = "a,b,,c"
print(text.split(",")) # ['a', 'b', '', 'c']
print("".split(",")) # ['']Two details in this output matter.
- Two separators in a row produce an empty string between them. The pieces are never merged or skipped.
- An empty input string produces a list with one empty string, not an empty list.
The diagram shows the first case. Each comma ends one piece. The second comma ends an empty piece, so the result has four items.
The length rule
For a non-empty separator, a string with n non-overlapping separators always splits into exactly n + 1 pieces. This rule explains every edge case below.
text = "a,b,,c"
print(len(text.split(","))) # 4
print(text.count(",") + 1) # 4
print("".split(",")) # [''] 0 separators, 1 piece
print(",".split(",")) # ['', ''] 1 separator, 2 piecesThe rule covers the empty string too. "" contains no separators, so it gives one piece, and that piece is empty.
Leading and trailing separators
A separator at the start or end of the string creates an empty piece at that end. split does not trim these.
print(",a,b,".split(",")) # ['', 'a', 'b', '']
print(",,".split(",")) # ['', '', '']This matters when you parse data that may begin or end with the separator, such as a path like /usr/local/bin.
path = "/usr/local/bin"
print(path.split("/")) # ['', 'usr', 'local', 'bin']The first item is an empty string because the path starts with a slash. If you want only the real components, filter out the empty ones:
path = "/usr/local/bin"
components = [p for p in path.split("/") if p]
print(components) # ['usr', 'local', 'bin']The condition if p keeps non-empty strings and drops empty ones. Use this filter only when empty fields carry no meaning in your data. In a table row such as a,,c, the empty field is a real value, and removing it shifts every later column.
Separators longer than one character
The separator can be a string of any length. split matches the whole string, not any of its characters.
print("a--b--c".split("--")) # ['a', 'b', 'c']
print("a-b--c".split("--")) # ['a-b', 'c']
print("one, two, three".split(", ")) # ['one', 'two', 'three']In the second line, the single hyphens are not separators, because only the two-character sequence -- matches. Don't write split("ab") and expect it to split on either a or b. Splitting on any one of several characters needs a regular expression, which a later chapter covers.
Overlapping matches
Matches never overlap. split takes the leftmost match, then continues scanning after it.
print("aaa".split("aa")) # ['', 'a']
print("aaaa".split("aa")) # ['', '', '']In "aaa", the first aa sits at positions 0 and 1. Scanning resumes at position 2, which holds only a single a, so it can't match. The result is an empty piece before the match and 'a' after it. The length rule still holds, because "aaa".count("aa") is also 1, and count also skips overlapping matches.
Matching is exact
The separator must match exactly, including case.
print("aXbxc".split("x")) # ['aX', 'bxc'[:1], 'c']That example would be misleading, so here is the correct and complete form:
print("aXbxc".split("x")) # ['aXb', 'c']
print("aXbxc".split("X")) # ['a', 'bxc']Only the lowercase x splits in the first line. For case-insensitive splitting, use re.split with the re.IGNORECASE flag, or normalise the case first with text.lower() if losing the original case is acceptable.
Invalid separators
Two mistakes raise exceptions instead of returning a list.
text = "abc"
try:
text.split("")
except ValueError as e:
print("ValueError:", e) # ValueError: empty separator
try:
text.split(1)
except TypeError as e:
print("TypeError:", e)An empty separator is rejected because it would match between every pair of characters, and the result would be ambiguous. To get the characters of a string, use list(text). A separator that is not a string, such as an integer, raises TypeError. If you have a number, convert it first with str().
Separators and string types must also agree. A bytes object splits with a bytes separator (b"a,b".split(b",")), and mixing str and bytes raises TypeError.
Every piece is a string
split knows nothing about the content of the pieces. Digits come back as strings, and you must convert them yourself.
line = "10,20,30"
fields = line.split(",")
print(fields) # ['10', '20', '30']
print(sum(fields) if False else "") # (sum would fail on strings)
numbers = [int(f) for f in fields]
print(numbers) # [10, 20, 30]
print(sum(numbers)) # 60The sum(fields) if False else "" line is a stand-in to show that summing strings is not valid. In real code, convert first, then compute.
A conversion such as int("") raises ValueError, which is how empty fields tend to surface in real programs. Decide in advance what an empty field means: skip it, use a default such as 0, or report an error.
Spaces around separators are kept
split(",") does not remove spaces. If the data has a space after each comma, the space becomes part of the following piece.
text = "red, green ,blue"
print(text.split(",")) # ['red', ' green ', 'blue']
clean = [item.strip() for item in text.split(",")]
print(clean) # ['red', 'green', 'blue']strip() removes whitespace from both ends of each piece. When the format is always a comma followed by exactly one space, you can instead split on the two-character separator ", ". That is fragile, because one stray space in the input breaks it. Splitting on "," and stripping each piece is the safer choice.
Unpacking the result
When a line always has a fixed number of fields, you can unpack the list into names.
line = "Ada,36,London"
name, age, city = line.split(",")
print(name, int(age), city) # Ada 36 LondonThis fails with ValueError if the line has a different number of fields.
try:
name, age = "Ada,36,London".split(",")
except ValueError as e:
print(e) # too many values to unpack (expected 2)Malformed input is the usual cause, but a value that itself contains the separator (for example "Ada,36,London, UK") has the same effect. Check len(fields) when the input is not under your control. The next chapters show two better options for "split at most once": maxsplit and partition.
Splitting inside loops
A common pattern is to split every line in a block of text. Combine split with a loop or comprehension:
rows = ["Ada,36", "Grace,45", "Alan,41"]
for row in rows:
name, age = row.split(",")
print(f"{name} is {age}")
people = [row.split(",") for row in rows]
print(people) # [['Ada', '36'], ['Grace', '45'], ['Alan', '41']]Each call creates a fresh list, so the result is a list of lists. Changing one inner list doesn't affect the original strings in rows.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `text` is unchanged after `text.split(",")` | The returned list was not stored | Assign it: `parts = text.split(",")` |
| An unexpected `''` at the start or end | A leading or trailing separator | Filter with `if p`, or check your input |
| `['']` instead of `[]` for empty input | `split` with a separator always returns at least one piece | Test `if text:` first, or filter |
| `ValueError: empty separator` | Calling `split("")` | Use `list(text)` for characters |
| `TypeError` from the separator | The separator is an int or other non-string | Convert with `str()` |
| `ValueError: too many values to unpack` | The field count differs from the number of names | Check `len(fields)` or limit the splits |
| Fields still contain spaces | `split(",")` keeps surrounding spaces | Apply `.strip()` to each piece |
A complete example
This script parses a small block of comma-separated settings, tolerating spaces and one blank line.
config = """\
host = example.com
port = 8080
debug = true
"""
settings = {}
for line in config.split("\n"):
if not line:
continue
key, value = line.split("=")
settings[key.strip()] = value.strip()
print(settings)
# {'host': 'example.com', 'port': '8080', 'debug': 'true'}The trailing newline in config makes config.split("\n") end with an empty string, so the if not line check is needed. A later chapter shows why splitlines() is often a better choice for this task. The script also assumes exactly one = per line, which is the same fragility described in the unpacking section.
Summary of rules
split(sep)returns a new list and never changes the original string.- A non-empty separator that occurs
ntimes, without overlap, givesn + 1pieces. - Consecutive, leading and trailing separators produce empty strings.
"".split(",")returns[''], not[].- The separator must be a non-empty
strthat matches exactly, including case. - Every piece is a
str. Convert numbers yourself, andstrip()any padding.
Exercise
What does each of these print? (a) ",a,,b".split(",") (b) "x--y---z".split("--") (c) len("".split(","))
Show answer
(a) ['', 'a', '', 'b']. There are three commas, so there are four pieces, and the leading comma and the double comma each produce an empty string. (b) ['x', 'y', '-z']. The scan finds -- after x, then -- at the start of ---, leaving a single - attached to z. (c) 1, because splitting an empty string on a separator returns a list holding one empty string.
Exercise
The string row = "Ada, 36 ,London" should become the list ['Ada', '36', 'London'], with the age as the string '36'. Write a one-line expression that does this, and say why row.split(",") alone is not enough.
Show answer
[f.strip() for f in row.split(",")]. Plain row.split(",") returns ['Ada', ' 36 ', 'London'], because split with an explicit separator keeps the spaces around the commas. strip() removes them from each piece.