Splitting Strings

Concepts covered: Splitting & Joining

str.split cuts a string at every occurrence of a separator and returns the pieces as a list: an ordered sequence of values, printed between square brackets with each string in quotes. Lists get their own lesson later, and this lesson needs 3 facts about them. A for loop walks a list item by item, multiple assignment unpacks it into named variables, and [0] reads its first item the way [0] reads the first character of a string.

Whitespace splitting versus a fixed separator

Called with no argument, split() treats any run of whitespace, newlines included, as a single separator and ignores whitespace at both ends. Called with an argument, split(" ") cuts at every single space, so 2 spaces in a row leave an empty string between them. Log files padded for alignment trip up the second form and pass cleanly through the first.

line = "203.0.113.7  GET /checkout 200 1532"
print(line.split(" "))
print(line.split())
ip, method, path, status, size = line.split()
print(method, path, int(size) * 2)

Output:

['203.0.113.7', '', 'GET', '/checkout', '200', '1532']
['203.0.113.7', 'GET', '/checkout', '200', '1532']
GET /checkout 3064

Even '200' and '1532' come back as strings, like every other piece, so arithmetic needs int() first; the last line converts size before doubling it. The unpacking line shows the usual next step after a split: naming each field, so later code reads path instead of a position.

split()
  • Any run of whitespace counts as a single cut
  • Whitespace at both ends is ignored
  • Never returns an empty string as a piece
split(sep)
  • Every occurrence of sep is a cut
  • A separator at either end makes an empty field
  • n separators give n + 1 pieces

The empty string in the first result follows a fixed rule: each separator ends the field before it, and whatever follows the last separator forms a final field, even when nothing follows. The program below makes those cuts by hand with find, printing every field between brackets so an empty one stays visible.

text = "a,,b,"
start = 0
while True:
    cut = text.find(",", start)
    if cut == -1:
        print("[" + text[start:] + "]")
        break
    print("[" + text[start:cut] + "]")
    start = cut + 1
[a]
[]
[b]
[]

Edge cases worth predicting

ExpressionResultWhy
`"a,b,".split(",")``['a', 'b', '']`Text after the last comma is a field
`"".split(",")``['']`No separator found, so 1 field, and it is empty
`"".split()``[]`No-argument split drops empty pieces
`" a b ".split()``['a', 'b']`Runs count once, and the ends are trimmed
`"a\r\nb\n".split("\n")``['a\r', 'b', '']`Windows line endings leave `\r` behind
`"a\r\nb\n".splitlines()``['a', 'b']`Cuts at any line ending, with no empty last field

Capping the number of cuts

The second argument, maxsplit, caps how many cuts happen, and everything after the last cut stays in a single piece. A header such as time: 12:30:05 shows why it matters: a plain split(":") cuts the clock apart too. rsplit takes its cuts from the right end, the end that holds a file extension.

header = "time: 12:30:05"
print(header.split(":"))
print(header.split(":", 1))
name = "logs/2024/app.tar.gz"
print(name.split(".", 1))
print(name.rsplit(".", 1))

Output:

['time', ' 12', '30', '05']
['time', ' 12:30:05']
['logs/2024/app', 'tar.gz']
['logs/2024/app.tar', 'gz']

When the piece count is wrong

Multiple assignment demands an exact count. key, value = text.split("=") works for mode=fast, raises ValueError for url=/a?b=c, whose 2 equals signs produce 3 pieces, and raises again for debug, which has no equals sign and produces 1 piece.

for text in ["mode=fast", "url=/a?b=c", "debug"]:
    try:
        key, value = text.split("=")
        print("ok:", key, value)
    except ValueError as err:
        print("ValueError:", err)

Output:

ok: mode fast
ValueError: too many values to unpack (expected 2)
ValueError: not enough values to unpack (expected 2, got 1)

Passing maxsplit=1 repairs the URL case. partition(sep) repairs all 3: it always returns exactly 3 values, with the separator itself in the middle between the text before it and the rest. When the separator is missing, the last 2 come back as empty strings, so a 3-name assignment never fails.

for text in ["mode=fast", "url=/a?b=c", "debug"]:
    key, sep, value = text.partition("=")
    print(key + "|" + sep + "|" + value)

Output:

mode|=|fast
url|=|/a?b=c
debug||

What does this program print?

row = ",GET,,200,"
print(row.split(","))

An address such as cache:primary:6379 has a colon inside its name as well as before its port. The port is always the last field, so the cut belongs at the last colon: rsplit(":", 1) gives 2 pieces, while split(":") gives 3 and breaks a 2-name unpacking.

The 2 repairs differ when the separator is missing. "debug".split("=", 1) still returns 1 piece and still fails a 2-name unpacking, which suits code that must reject a malformed setting. partition returns empty strings instead, which suits code that treats a bare key as a flag.

About this lesson

This section is part of the Strings: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.