How to concatenate strings in Python
Use f-strings for readability: f'{a}{b}'. Use ''.join(list) when joining many strings — a + b + c is O(n²) in a loop.
first = "Alice"
last = "Smith"
full = f"{first} {last}" # 'Alice Smith' — idiomatic
full = first + " " + last # same result, less readable
full = " ".join([first, last]) # best for many partsf-strings (Python 3.6+) are the modern default: readable, fast, and handle inline expressions. f'{first} {last}' outperforms '{} {}'.format(first, last) and ("%s %s" % (first, last)) on both benchmarks and code review.
For concatenating many strings — like joining lines of a file or elements of a list — use ''.join(iterable). It allocates the result buffer once. Repeated += in a loop is O(n²) because strings are immutable, so each iteration builds a new string.
The delimiter goes before .join: ' '.join(words) joins with spaces, ','.join(fields) joins with commas.
Variations
Join a list
words = ["hello", "world", "python"]
print(" ".join(words)) # 'hello world python'One allocation, O(n). Every element must already be a string.
Join with a newline
print("\n".join(["line 1", "line 2", "line 3"]))Common for building multi-line output.
join() with non-strings → map(str, ...)
nums = [1, 2, 3]
print(", ".join(str(n) for n in nums)) # '1, 2, 3'join() requires strings — convert first.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.