liveBook · Manning

Join

As explained in Python Workout: 50 ten-minute exercises

str.join is a Python string method that concatenates an iterable of strings with the calling string placed between adjacent elements.

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

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains separators, string-only inputs, comprehensions, and list-based accumulation, while deferring iterator-protocol details.
Examples
Demonstrates sorted characters, Pig Latin output, XML attributes, translated words, and comma-separated numbers.
What it assumes
Assumes familiarity with strings and iteration, while reinforcing that strings are sequences and comprehensions transform iterables.
What you can do after
Apply it via Python's str.join to assemble strings from compatible iterable elements and separators.
How it connects
Connects str.join with strings as sequences, str.split, sorted, list comprehensions, and mutable lists.

Also explained in

Compare how 6 books explain join →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.