Sub topic 10
Splitting text apart and joining it back
This chapter assumes you know Python variables, lists, tuples, for loops, and that strings are immutable, so every method here returns a new value. Splitting turns one string into pieces. Joining builds one string from pieces.
split with a separator
str.split(sep) cuts the string at every occurrence of sep and returns a list. Empty fields are kept, which matters for data like CSV rows.
print("a,b,,c".split(",")) # ['a', 'b', '', 'c']
print("a,b,c".split(",", 1)) # ['a', 'b,c']The optional second argument, maxsplit, limits the number of cuts. With maxsplit=1 you get at most two pieces.
split with no arguments
Calling split() with no separator behaves differently. It splits on any run of whitespace and drops empty strings, including those at the ends.
print(" a b \n c".split()) # ['a', 'b', 'c']
print(" a b ".split(" ")) # ['', '', 'a', '', 'b', '']The second line shows the common mistake. Passing " " explicitly splits on every single space, so you get empty strings.
rsplit, splitlines, and partition
rsplit works like split but counts from the right when you give maxsplit. That is useful for peeling off a file extension or the last field.
splitlines splits on line boundaries such as \n and \r\n. It does not leave an empty last item for a trailing newline, which split("\n") does.
partition splits once, at the first match, and always returns a three-item tuple: the part before, the separator, and the part after. If the separator is missing, you get the whole string and two empty strings. rpartition does the same from the right.
text = "line1\nline2\n"
print(text.splitlines()) # ['line1', 'line2']
print(text.split("\n")) # ['line1', 'line2', '']
print("a b c".rsplit(" ", 1)) # ['a b', 'c']
print("key=value=x".partition("=")) # ('key', '=', 'value=x')
print("novalue".partition("=")) # ('novalue', '', '')join
sep.join(iterable) is a method of the separator, not of the list. It places sep between the items and returns one string. Every item must already be a str.
print(", ".join(["a", "b", "c"])) # a, b, c
print("".join(["x", "y"])) # xy
numbers = [1, 2, 3]
print("-".join(str(n) for n in numbers)) # 1-2-3The round trip
Splitting and joining together make a small cleanup pattern. Splitting on whitespace and rejoining with one space normalizes spacing.
raw = " Hello World "
clean = " ".join(raw.split()).lower()
print(clean) # hello worldChoosing the right method
| Need | Method |
|---|---|
| Fields separated by a known character, empties kept | `split(sep)` |
| Words separated by any whitespace | `split()` |
| Only the last piece | `rsplit(sep, 1)` |
| Lines of text | `splitlines()` |
| Exactly one split, safe if missing | `partition(sep)` |
| Pieces back into one string | `sep.join(items)` |
Exercise
What does "a,b,,c".split(",") return, and how does " a b ".split() differ from " a b ".split(" ")?
Show answer
The first returns ['a', 'b', '', 'c'], keeping the empty field. " a b ".split() returns ['a', 'b'], because with no argument it splits on runs of whitespace and discards empties. " a b ".split(" ") returns ['', '', 'a', '', 'b', ''], because it cuts at every single space.
Exercise
Given line = "host=example.com=8080", how do you get the key "host" and the rest "example.com=8080", and what do you get if the line has no "="?
Show answer
Use key, sep, value = line.partition("="). This gives key "host" and value "example.com=8080". With no "=", key is the whole line, and sep and value are both empty strings.