Sub topic 10
Splitting text apart and joining it back
This chapter assumes you know basic str indexing, lists and tuples, and for loops. Earlier chapters showed that string methods return new strings. The methods here go a step further: they turn one string into a list or tuple of pieces, and turn pieces back into one string.
The split family at a glance
| Method | Returns | Splits | Best for |
|---|---|---|---|
| `split(sep)` | list | on every `sep` | delimited fields |
| `split()` | list | on runs of whitespace | words |
| `rsplit(sep, n)` | list | from the right, at most `n` times | peeling off trailing parts |
| `splitlines()` | list | on line boundaries | multi-line text |
| `partition(sep)` | 3-tuple | once, at the first `sep` | `key=value` pairs |
| `rpartition(sep)` | 3-tuple | once, at the last `sep` | file extensions, last segment |
| `sep.join(items)` | string | joins items with `sep` | rebuilding text |
split with a separator
split(sep) cuts the string at every occurrence of sep and returns a list. The separator is not part of any piece, and empty fields are kept.
print("a,b,,c".split(",")) # ['a', 'b', '', 'c']
print(",a,".split(",")) # ['', 'a', '']
print("".split(",")) # ['']Two details matter here:
- The number of pieces is always one more than the number of separators. That is why
",a,"produces an empty string at each end. - Splitting an empty string with a separator gives
[''], a list with one empty string, not an empty list. Code that loops over the result runs once, with empty input.
The separator can be longer than one character, for example "a--b".split("--"). It cannot be empty: "abc".split("") raises ValueError: empty separator. Use list("abc") to get single characters.
split with no arguments
Calling split() with no separator, or with None, uses different rules. It treats any run of whitespace (spaces, tabs, newlines) as one separator and discards empty strings at the ends.
print(" a b \t c\n".split()) # ['a', 'b', 'c']
print("".split()) # []
print(" ".split()) # []For splitting text into words this is almost always what you want, since you get no empty strings and no need to call strip first. The empty-input case returns [], which is the opposite of the separator form.
Limiting the number of splits
The second parameter, maxsplit, caps the number of cuts. The result then has at most maxsplit + 1 items, and the last item holds the unsplit remainder.
print("a,b,c,d".split(",", 2)) # ['a', 'b', 'c,d']
print("a,b,c,d".rsplit(",", 2)) # ['a,b', 'c', 'd']
print("a b c".rsplit(" ", 1)) # ['a b', 'c']
print(" a b ".split(None, 1)) # ['a', 'b ']Without maxsplit, split and rsplit give identical results. rsplit differs only when a limit is set, because it counts cuts from the right. Pass None as the separator when you want whitespace splitting and a limit. The last line shows that the remainder keeps its trailing whitespace, since only the cut point is consumed.
splitlines
You might split text into lines with split("\n"). That has two problems. It leaves a trailing empty string when the text ends with a newline, and it ignores Windows \r\n endings. splitlines() handles both.
text = "line1\nline2\r\nline3\n"
print(text.split("\n")) # ['line1', 'line2\r', 'line3', '']
print(text.splitlines()) # ['line1', 'line2', 'line3']
print(text.splitlines(True)) # ['line1\n', 'line2\r\n', 'line3\n']Passing True (the keepends argument) keeps the line endings on each piece. This lets you reassemble the original text exactly with "".join(...). splitlines also recognizes other boundaries, such as \r, \x0b, \x0c, and the Unicode line separator. That is useful for text from unknown sources, but can surprise you if the data contains those characters inside a record.
partition and rpartition
When you need exactly two parts, partition is clearer than split with a limit. It always returns a 3-tuple: the text before the separator, the separator, and the text after.
print("key=value=x".partition("=")) # ('key', '=', 'value=x')
print("key=value=x".rpartition("=")) # ('key=value', '=', 'x')
print("novalue".partition("=")) # ('novalue', '', '')
print("novalue".rpartition("=")) # ('', '', 'novalue')The tuple always has three items, so unpacking never fails. With split("=", 1) a missing separator gives a one-item list, and key, value = line.split("=", 1) raises ValueError. With partition you detect a missing separator by checking whether the middle item is empty. Note where the unsplit text lands when nothing matches: with partition it is the first item, with rpartition it is the last.
join
join is the inverse of split, but it is called on the separator, not on the list:
parts = ["a", "b", "c"]
print(", ".join(parts)) # a, b, c
print("".join(parts)) # abc
print("-".join("abc")) # a-b-cThe last line works because a string is an iterable of one-character strings. The method takes any iterable, including generators, and builds the result in one pass. That makes it much faster than concatenating with += in a loop, which can copy the growing string repeatedly.
Every item must be a str. Numbers raise TypeError, so convert them first:
nums = [1, 2, 3]
# ",".join(nums) -> TypeError: sequence item 0: expected str instance, int found
print(",".join(str(n) for n in nums)) # 1,2,3
print(",".join(map(str, nums))) # 1,2,3Another common slip is writing parts.join(", "). Lists have no join method, so this raises AttributeError. The string doing the joining comes first.
A worked example: parsing a small config
This script combines splitlines, strip, startswith, and partition. It skips blank lines and comments, and splits each remaining line at its first =.
text = """
name = Ada
# a comment
role = engineer = lead
empty =
"""
settings = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
key, sep, value = line.partition("=")
if not sep:
continue # no "=" on this line
settings[key.strip()] = value.strip()
print(settings)
# {'name': 'Ada', 'role': 'engineer = lead', 'empty': ''}partition splits at the first = only, so a value that contains = stays intact. This is the reason to prefer it here over a plain split("=").
Round trips and normalizing spacing
split() followed by " ".join(...) collapses any run of whitespace to one space:
raw = " Hello \t World \n"
print(" ".join(raw.split())) # Hello WorldThis round trip is not lossless in general. Splitting on a separator and rejoining with the same separator restores the original string. Splitting on whitespace discards information about what kind of whitespace was there and how much.
For text with line endings, the lossless pair is splitlines(True) with "".join(...).
Common errors
- Expecting
split(",")to drop empty fields. It keeps them. Filter with[p for p in s.split(",") if p]if you want to remove them. - Confusing
"".split(",")(['']) with"".split()([]). - Using
split(" ")to split words. Two spaces in a row produce an empty string. Usesplit(). - Forgetting to convert non-strings before
join. - Calling
joinon the list instead of the separator. - Ignoring the unsplit remainder when you set
maxsplit. The last item can still contain the separator.
When split is not enough
The built-in methods split on a fixed piece of text. They cannot handle several different separators at once, patterns such as "a comma followed by optional spaces", or quoted fields. Quoted fields are the usual failure with CSV data. The line 'a,"b,c",d' splits into four pieces with split(","), but it holds three fields.
For several separators, re.split works:
import re
print(re.split(r"[,;]\s*", "a, b;c")) # ['a', 'b', 'c']For real CSV data, use the csv module, which understands quoting. A later chapter covers where to draw the line between string methods and re.
Exercises
Exercise
What does "a,,b".split(",") return, and how would you get ['a', 'b'] instead?
Show answer
It returns ['a', '', 'b'] because separator splitting keeps empty fields. To drop them, filter the result: [p for p in "a,,b".split(",") if p]. If the separator were whitespace, plain split() would already skip empties.
Exercise
Given path = "/usr/local/bin/python", use one method call to get the directory ("/usr/local/bin") and the file name ("python"). Then explain why partition("/") would not work.
Show answer
directory, _, filename = path.rpartition("/") gives directory == "/usr/local/bin" and filename == "python". partition("/") cuts at the first "/", which is the leading one, so it returns ('', '/', 'usr/local/bin/python'). rpartition cuts at the last separator, which is the one you want.
Exercise
This line raises an error: ",".join([1, 2, 3]). Name the error and write a corrected version that prints 1,2,3.
Show answer
It raises TypeError, because join requires every item to be a str. Corrected: print(",".join(str(n) for n in [1, 2, 3])), or print(",".join(map(str, [1, 2, 3]))).