Sub topic 10
Round trips: when split and join undo each other
This chapter assumes you know str.split, str.join, and basic list and tuple handling. It covers when sep.join(text.split(sep)) gives back the original text, and when it does not.
The round trip idea
split and join are inverse operations in one specific case. If you split on an explicit separator and join with the same separator, you get the original string back.
text = "a,b,,c"
parts = text.split(",")
print(parts) # ['a', 'b', '', 'c']
print(",".join(parts) == text) # TrueThis works because split(sep) keeps every field, including empty ones. Consecutive separators become empty strings, and join puts a separator back between each pair of items, so the empty strings reproduce the doubled separator.
The same holds at the edges of the string.
for text in ["", ",", ",a", "a,", ",,"]:
parts = text.split(",")
print(repr(text), parts, ",".join(parts) == text)Each line prints True. A leading or trailing separator produces an empty string at that end of the list, and join restores it.
When the round trip breaks
The round trip fails whenever split throws information away. Three common cases follow.
Whitespace splitting
split() with no argument collapses runs of whitespace and drops leading and trailing whitespace. That information is gone, so join cannot restore it.
line = " hello world \n"
parts = line.split()
print(parts) # ['hello', 'world']
print(" ".join(parts) == line) # False
print(repr(" ".join(parts))) # 'hello world'This is often what you want, since it normalizes spacing. Just do not expect the original back.
Limited splits with different separators
maxsplit does not break the round trip if you use the same separator, because the unsplit remainder stays intact.
text = "key=value=more"
parts = text.split("=", 1)
print(parts) # ['key', 'value=more']
print("=".join(parts) == text) # TrueLine endings
splitlines removes the line endings and does not record which kind each line had. A \n, \r\n and a trailing newline all disappear.
data = "one\ntwo\r\nthree\n"
lines = data.splitlines()
print("\n".join(lines) == data) # False
print(repr("\n".join(lines))) # 'one\ntwo\nthree'If you need an exact round trip, use splitlines(True) and join with the empty string.
data = "one\ntwo\r\nthree\n"
print("".join(data.splitlines(True)) == data) # TruePattern splitting
re.split with a pattern loses the matched text, since different matches can differ. Splitting "a, b;c,d" on [,;]\s* gives ['a', 'b', 'c', 'd'], and nothing tells you which separator sat between which items. A capturing group keeps the separators in the list, so "".join(re.split(r"(\d)", "a1b2c")) returns 'a1b2c'.
A summary of the cases
| Operation | Round trip with `join`? | What is lost |
|---|---|---|
| `s.split(sep)` | Yes, with `sep.join` | Nothing |
| `s.split(sep, n)` | Yes, with `sep.join` | Nothing |
| `s.split()` | No | Whitespace type, run length, edges |
| `s.splitlines()` | No | Line ending type, final newline |
| `s.splitlines(True)` | Yes, with `"".join` | Nothing |
| `re.split(pattern, s)` | No | The matched separators |
| `re.split("(pattern)", s)` | Yes, with `"".join` | Nothing |
Using the round trip on purpose
You can use these properties for safe text edits. Split on one separator, change the items, then join with the same or a different separator.
path = "usr/local/bin"
parts = path.split("/")
print("\\".join(parts)) # usr\local\binYou can also use the round trip as a test. If sep.join(s.split(sep)) != s for an input, something other than an explicit separator is involved.
A common mistake
A round trip also fails if the data itself contains the separator in a place you did not plan for. Joining ["a,b", "c"] with a comma gives 'a,b,c', and splitting that gives three items, not two. The join was fine. The structure was lost because the separator appears inside an item. The csv chapter later in this tutorial covers quoting as the fix.
Exercise
Which of these expressions evaluate to True? (1) " ".join("a b".split(" ")) == "a b" (2) " ".join("a b".split()) == "a b" (3) "".join("x\ny\n".splitlines(True)) == "x\ny\n"
Show answer
(1) and (3). Splitting on a single space keeps the empty string between the two spaces, so joining restores both spaces. split() collapses the two spaces into one, so (2) gives "a b". splitlines(True) keeps the line endings, so joining with an empty string restores the text.
Exercise
A function receives text and must return it with every comma replaced by a semicolon, using split and join. Write it, and say why it needs no special handling of empty fields.
Show answer
def swap(text): return ";".join(text.split(",")) Splitting on an explicit separator keeps empty fields, so "a,,b" becomes ['a', '', 'b'] and then "a;;b". No information is lost, so no special case is needed.