When a transformation produces several pieces of text, collect those pieces and use str.join to combine them. The calling string becomes the separator: ''.join(parts) produces one continuous string, while ','.join(parts) places commas between elements. section 2.18 section 2.13
Use join in these common patterns:
- Convert a sorted string back from the list returned by sorted: ''.join(sorted(text)). section 2.18
- Build repeated output efficiently by appending pieces to a list and joining once, rather than repeatedly using += on an immutable string. section 2.8
- Convert non-string values before joining, commonly with a comprehension: ','.join(str(number) for number in numbers). section 7.2
Joining numbers
numbers = range(15) print(','.join(str(number) for number in numbers)) The conversion is necessary because join expects strings, not integers. The generator expression supplies one converted string at a time. section 7.2
>>> numbers = range(15) >>> ','.join(numbers) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected str instance, int found
Inspect the failed call to see the type requirement that motivates conversion before joining. section 7.2
numbers = range(15)
print(','.join(str(number)
for number in numbers))
Compare the failing integer example with a complete comma-separated output pattern. section 7.2





