Sub topic 10
Round trips: when split and join undo each other
This chapter covers when split followed by join gives back the original string, and when information is lost along the way. It assumes you know basic Python syntax, how strings, lists and tuples behave, and how to call a method and read its return value. It also assumes you have met str.split, rsplit, splitlines, partition and str.join from earlier chapters. Here the focus is on what each pair preserves and what it discards.
Why round trips matter
Programs often take text apart, change some of the pieces and put the text back together. You might split a path, rename one component and rebuild it. You might split a line into words, filter them and write the line back out.
This works only if the two steps are compatible. If splitting throws away information, joining cannot restore it. If joining produces text that splitting reads differently, the data changes. Knowing which operations are lossless saves you from bugs that appear only on edge-case input, such as empty strings, repeated separators or a separator inside a value.
Two directions are worth testing separately:
- Text round trip:
sep.join(text.split(sep)) == text - List round trip:
sep.join(items).split(sep) == items
These two properties have different guarantees. The first is almost always true. The second often fails.
Text, list, text: the safe direction
Splitting on an explicit, non-empty separator keeps every character of the input except the separators. It also keeps empty fields. Joining with the same separator puts the separators back in the same places.
text = "a,b,,c,"
parts = text.split(",")
print(parts) # ['a', 'b', '', 'c', '']
print(",".join(parts) == text) # TrueThe empty strings are what make this work. The doubled comma produced one empty field in the middle, and the trailing comma produced one at the end. Joining writes a separator between each pair of neighbours, so it recreates both.
You can check the property on awkward inputs, including the empty string:
def text_round_trips(text, sep):
return sep.join(text.split(sep)) == text
for sample in ["", "a", ",", ",,", "a,,b", ",a,"]:
print(repr(sample), text_round_trips(sample, ","))Every line prints True. The empty string works because "".split(",") returns [''], and joining a one-item list returns that item unchanged.
The guarantee also holds when you limit the number of splits. With maxsplit, the last item keeps the unsplit remainder, separators included, so the join still matches. rsplit works the same way from the other end.
text = "key=value=more"
print("=".join(text.split("=", 1)) == text) # True
print("/".join("a/b/c/d".rsplit("/", 1)) == "a/b/c/d") # TrueThe guarantee depends on one condition: the separator must be an explicit string. An empty separator is not allowed, and "abc".split("") raises ValueError.
List, text, list: the unsafe direction
Going the other way, you start with a list, join it, and split the result. The list comes back only if two conditions hold:
- No item contains the separator.
- The list is not empty.
items = ["a", "b", "c"]
print(",".join(items).split(",") == items) # TrueNow break each condition in turn.
print(",".join(["a,b", "c"]).split(",")) # ['a', 'b', 'c']
print(",".join([]).split(",")) # ['']
print(",".join([""]).split(",")) # ['']In the first line, the item "a,b" contained the separator, so it became two items. The data was changed with no error.
The second and third lines show that two different lists, [] and [''], both join to the empty string. Splitting that string can return only one answer, and it returns ['']. So join is not one-to-one: different inputs can give the same output, and no function can undo it for all inputs. An empty list does not survive a round trip through a plain separator-joined string.
Choosing a separator that cannot appear
If you control the data, you can sometimes pick a separator that will not occur in any item. A tab, a newline or a control character such as "\x1f" (the ASCII unit separator) rarely shows up in ordinary values. You should still validate rather than hope:
def safe_join(items, sep):
for item in items:
if sep in item:
raise ValueError(f"item {item!r} contains the separator")
return sep.join(items)
print(safe_join(["a", "b"], ",")) # a,b
try:
safe_join(["a,b", "c"], ",")
except ValueError as error:
print(error) # item 'a,b' contains the separatorFailing loudly is better than a silent change. Handling the empty-list case still needs a convention, for example storing a missing value in a different way.
Whitespace splitting is lossy
split() with no argument treats any run of whitespace as one separator and discards leading and trailing whitespace. This is useful for reading words, but the result cannot be turned back into the original.
line = " hello world \n"
words = line.split()
print(words) # ['hello', 'world']
print(" ".join(words)) # hello world
print(" ".join(words) == line) # FalseThe spacing and the newline are gone for good. You can call " ".join(text.split()) on purpose as a way to normalize whitespace. It collapses every run of spaces, tabs and newlines to a single space and trims the ends. Use it when you want that effect, and do not use it when you need the original text back.
Compare split(" "), which splits on every single space and keeps the empty fields:
text = "a b"
print(" ".join(text.split(" ")) == text) # True
print(" ".join(text.split()) == text) # FalseThe explicit-separator version round-trips, and the no-argument version does not. Many "mystery" whitespace bugs come from using one form when you meant the other.
Lines: splitlines and its options
"\n".join(text.splitlines()) looks like a round trip, but it is not one. splitlines recognises several line endings, including \n and \r\n, and it drops them. It also does not produce a trailing empty item for a final newline.
data = "one\ntwo\r\nthree\n"
lines = data.splitlines()
print(lines) # ['one', 'two', 'three']
print("\n".join(lines) == data) # False
print("\n".join(lines)) # prints the three lines, with no final newlineTwo things were lost: the \r in the second line ending, and the newline after three. If you need the exact text back, ask splitlines to keep the endings and join with an empty string:
kept = data.splitlines(True)
print(kept) # ['one\n', 'two\r\n', 'three\n']
print("".join(kept) == data) # TrueNow each piece carries its own ending, so there is nothing to restore. This is the right choice for tools that edit a file line by line and must leave untouched lines byte-for-byte identical.
If you use split("\n") instead, you keep the final empty string and the \r, and "\n".join(...) does round-trip. Whether that is better depends on whether you want \r cleaned up. Decide which you need before you pick the method.
partition always round-trips
partition returns a 3-tuple: the part before the first separator, the separator, and the part after it. When the separator is missing, you get the whole string and two empty strings. Because the separator is included in the result, joining the three pieces always gives the original.
for text in ["[email protected]", "no-at-sign", "@", ""]:
pieces = text.partition("@")
print(pieces, "".join(pieces) == text)All four lines end with True. rpartition has the same property for the last separator. This makes partition the safest tool when you only need to cut once and want nothing to vanish.
Regular expressions and capturing groups
re.split follows a rule that affects round trips. If the pattern has no capturing group, the matched separators are dropped. Different separators that match the same pattern then cannot be told apart afterwards.
import re
text = "a, b;c,d"
parts = re.split(r"[,;]\s*", text)
print(parts) # ['a', 'b', 'c', 'd']
print(",".join(parts) == text) # FalseThe original mixed commas, semicolons and spaces. After splitting, only the fields remain, so no single separator can rebuild the text.
If the pattern has a capturing group, the matched text is included in the result between the fields. When the group covers the whole separator, joining everything with an empty string restores the input:
text = "a, b;c,d"
pieces = re.split(r"([,;]\s*)", text)
print(pieces) # ['a', ', ', 'b', ';', 'c', ',', 'd']
print("".join(pieces) == text) # TrueThe group must capture the entire separator. In the earlier pattern (\d), the group captures the digit, which is the whole separator, so "".join(re.split(r"(\d)", "a1b2c")) equals "a1b2c". If the group captured only part of the separator, the rest would be lost.
With a capturing group, the fields sit at even positions (0, 2, 4, ...) and the separators sit at odd positions. You can use that to change the fields and keep the separators:
fields = pieces[0::2]
seps = pieces[1::2]
upper = []
for i, field in enumerate(fields):
upper.append(field.upper())
if i < len(seps):
upper.append(seps[i])
print("".join(upper)) # A, B;C,DValues that contain the separator
When a value may contain the separator, you cannot fix the problem with split and join alone. You need a format that marks which separators are data. The csv module does this with quoting.
import csv
import io
items = ["a,b", "c", ""]
buffer = io.StringIO()
csv.writer(buffer, lineterminator="").writerow(items)
text = buffer.getvalue()
print(text) # "a,b",c,
restored = next(csv.reader([text]))
print(restored) # ['a,b', 'c', '']
print(restored == items) # TrueThe writer put quotes around the item with a comma in it. The reader understood the quotes. This is a true list round trip, which ",".join could not give you. The cost is that the output is a csv-formatted line, and other programs must read it as csv.
Summary of guarantees
| Operation pair | Round trip holds? | What breaks it |
|---|---|---|
| `sep.join(text.split(sep))` | Yes, for any non-empty `sep` | Nothing |
| `sep.join(text.split(sep, n))` | Yes | Nothing |
| `sep.join(items).split(sep)` | Only sometimes | An item contains `sep`, or `items` is empty |
| `" ".join(text.split())` | No | Spacing, tabs, newlines and edge whitespace are lost |
| `"\n".join(text.splitlines())` | No | Line-ending type and the final newline are lost |
| `"".join(text.splitlines(True))` | Yes | Nothing |
| `"".join(text.partition(sep))` | Yes | Nothing |
| `"".join(re.split(pattern, text))` | No | Separators are dropped without a capturing group |
| `"".join(re.split("(pattern)", text))` | Yes, if the group covers the whole separator | A group that covers only part of the separator |
Exercise
Why does ",".join([]).split(",") return [''] instead of [], and what does this tell you about the list-to-text-to-list round trip?
Show answer
",".join([]) returns the empty string, and "".split(",") returns a list with one empty string. The lists [] and [''] both join to "", so the join step loses the difference between them and split cannot restore it. The round trip is safe only when the list is not empty and no item contains the separator.
Exercise
Given text = "a b" (two spaces), which of " ".join(text.split(" ")) and " ".join(text.split()) equals text, and why?
Show answer
The first one. text.split(" ") returns ['a', '', 'b'], keeping the empty field between the two spaces, so joining with one space rebuilds "a b". text.split() returns ['a', 'b'], because a run of whitespace counts as one separator, so the join gives "a b", which has one space.
Exercise
You read a file's text and want to rewrite one line and keep every other line, including \r\n endings and the final newline, exactly as it was. Which call should you use to split the text, and how do you join it back?
Show answer
Use lines = text.splitlines(True), which keeps each line ending as part of its item. Change the one item you need, then rebuild with "".join(lines). Because nothing was removed, the unchanged lines are identical to the original.