Sub topic 2
Splitting on a separator with str.split
This chapter covers str.split when you give it an explicit separator. It assumes you can run Python code, know what strings and lists are, and can call a method and read its return value.
What split does
str.split(sep) cuts a string at every occurrence of sep. It returns a list of the pieces. The separator itself is not kept.
text = "a,b,,c"
print(text.split(",")) # ['a', 'b', '', 'c']
print("".split(",")) # ['']The method returns a new list and leaves the original string unchanged. Strings cannot be modified in place, so you must store the result if you want to use it.
line = "x;y;z"
line.split(";") # result thrown away
print(line) # x;y;z
parts = line.split(";")
print(parts) # ['x', 'y', 'z']How the pieces are formed
The separator marks the boundaries between pieces. A string with N separators always gives N + 1 pieces. This rule explains every result in the first example.
The first comma sits between a and b. The second sits between b and the empty space before the third comma. The third sits between that empty space and c. The empty space becomes an empty string in the result.
Empty fields are kept
With an explicit separator, split never discards empty pieces. Two consecutive separators produce an empty string between them. A separator at the start or end of the string produces an empty string at that end.
print(",a,".split(",")) # ['', 'a', '']
print("a,,,b".split(",")) # ['a', '', '', 'b']This behavior is useful when position matters. In a record such as "Ada,,1815", the second field is missing, and the empty string keeps the third field in the third position.
It becomes a problem when you expect empty pieces to disappear. If you filter them out, you also lose the position information, so do that only when the positions don't matter.
raw = "a,b,,c"
fields = raw.split(",")
non_empty = [f for f in fields if f]
print(non_empty) # ['a', 'b', 'c']Empty input is not an empty list
An empty string contains zero separators, so it produces one piece: itself. The result is [''], not []. Code that loops over the result will run once, with an empty string.
items = "".split(",")
print(items) # ['']
print(len(items)) # 1Check for empty input first if you need an empty list.
def parse_tags(text):
return text.split(",") if text else []
print(parse_tags("")) # []
print(parse_tags("a,b")) # ['a', 'b']The separator is a literal string
The separator can be longer than one character. It is matched exactly as written, and it is not a pattern.
print("2026-11-26".split("-")) # ['2026', '11', '26']
print("one::two::three".split("::")) # ['one', 'two', 'three']
print("a.b.c".split(".")) # ['a', 'b', 'c']The dot in the last line is an ordinary dot. Characters that are special in regular expressions have no special meaning here. For pattern-based splitting you need re.split, which a later chapter covers.
Matches do not overlap. Python scans from the left and takes the first match, then continues after it.
print("aaaa".split("aa")) # ['', '', '']The first aa is at positions 0 to 1, and the second is at positions 2 to 3. That makes two separators and three pieces, all empty.
Common errors
- Passing an empty separator.
"abc".split("")raisesValueError: empty separator. To get a list of characters, uselist("abc"). - Expecting a string back. The result is always a list, even if no separator is found.
"abc".split(",")returns['abc']. - Unpacking a fixed number of fields.
a, b = "x,y,z".split(",")raisesValueErrorbecause there are three pieces. Check the count or limit the split, which a later chapter covers. - Forgetting that pieces are strings.
"1,2,3".split(",")gives['1', '2', '3']. Convert withintbefore doing arithmetic.
numbers = [int(p) for p in "1,2,3".split(",")]
print(sum(numbers)) # 6Summary of the rules
| Input | Result | Reason |
|---|---|---|
| `"a,b".split(",")` | `['a', 'b']` | One separator, two pieces |
| `"a,,b".split(",")` | `['a', '', 'b']` | Adjacent separators give an empty piece |
| `",a".split(",")` | `['', 'a']` | Leading separator gives a leading empty piece |
| `"".split(",")` | `['']` | Zero separators, one piece |
| `"abc".split(",")` | `['abc']` | Separator not found |
Exercise
What does "x,,y,".split(",") return, and how many pieces does it have? Explain using the separator count.
Show answer
It returns ['x', '', 'y', ''], which is four pieces. The string has three commas, and N separators always give N + 1 pieces. The double comma gives the empty string in the middle, and the trailing comma gives the empty string at the end.
Exercise
Write a function parse_ids(text) that turns "4,8,15" into [4, 8, 15] and returns an empty list for an empty string.
Show answer
def parse_ids(text): return [int(p) for p in text.split(",")] if text else []