Programming Search⌘K

Featurecore

Building strings

Also called str.join, string builder, io.StringIO, string concatenation in a loop, += on strings, quadratic concatenation, bytes.join.

A str cannot change, so each + makes a new string, and a loop of += can take quadratic time. Collect the parts in a list and call str.join() once, or write them to an io.StringIO.

Language
Python

Synopsis

words = ["spam", "eggs", "ham"]
print(", ".join(words))
print("-".join("Python"))
lines = []
for i in range(3):
    lines.append(f"line {i}")
print("\n".join(lines))
Output
spam, eggs, ham
P-y-t-h-o-n
line 0
line 1
line 2

The separator string calls join(), and the argument gives the parts. A loop adds parts to a list, and one join() at the end makes the string.

Semantics

r1. "Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length."1

r2. "To get a linear runtime cost, you must switch to one of the alternatives below: if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete".1

r3. str.join() returns "a string which is the concatenation of the strings in iterable."1 "A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method."1 Example: join-int.

r4. io.StringIO is "A text stream using an in-memory text buffer."2 getvalue() returns "a str containing the entire contents of the buffer."2 Example: stringio.

r5. For bytes, "you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object."1 Example: binary.

r6. CPython can sometimes make s += t fast, but PEP 8 says: "do not rely on CPython’s efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn’t present at all in implementations that don’t use refcounting."3

Examples

import io

out = io.StringIO()
out.write("total: ")
print(3, "items", file=out)
print("done", file=out)
text = out.getvalue()
print(repr(text))
Output
'total: 3 items\ndone\n'

print() can write to the buffer with file=, so code that prints to the screen can also build a string (rule r4).

row = (1, 2.5, None)
print(" | ".join(str(x) for x in row))
print("".join(c.upper() if i % 2 else c for i, c in enumerate("python")))
Output
1 | 2.5 | None
pYtHoN

join() accepts any iterable of strings, so a generator expression can convert the parts on the way.

import io

chunks = [b"GET ", b"/ ", b"HTTP/1.1"]
print(b"".join(chunks))
buf = bytearray()
for chunk in chunks:
    buf += chunk
print(bytes(buf) == b"".join(chunks))
stream = io.BytesIO()
stream.write(b"abc")
stream.write(b"def")
print(stream.getvalue())
Output
b'GET / HTTP/1.1'
True
b'abcdef'

A bytearray grows in place, so += on it does not copy the whole buffer each time (rule r5).

Pitfalls

A loop of += on a str gives the right result, but each step can copy the whole string (rules r1 and r6):

This code runs but gives a wrong answer on purpose.

s = ""
for i in range(5):
    s += str(i) + ","
print(s)
print("".join(str(i) + "," for i in range(5)))
Output
0,1,2,3,4,
0,1,2,3,4,

The two lines are equal. Use the join() form when the loop is long.

join() does not convert numbers:

This code raises TypeError, on purpose.

", ".join([1, 2, 3])

Convert each part first, as in ", ".join(map(str, [1, 2, 3])) (rule r3).

Comparison

Go has a type for this job: "A Builder is used to efficiently build a string using Builder.Write methods. It minimizes memory copying. The zero value is ready to use."4 Go strings.Builder is close to Python io.StringIO (rule r4). Go also has strings.Join(parts, sep), which takes the separator as the second argument, where Python calls sep.join(parts).

References

  1. Built-in Types, Python 3.15 documentation, Common Sequence Operations, notes; str.join()
  2. io, Core tools for working with streams, class io.StringIO; getvalue()
  3. PEP 8: Style Guide for Python Code, Programming Recommendations
  4. Package strings, Go standard library, type Builder

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source