Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.join() method

Reference for Python str.join(): concatenate an iterable of strings with a separator, why it beats += in loops, the TypeError for non-strings and common mistakes.

The join() method builds one string from an iterable of strings, putting the string it is called on between the items. ", ".join(["a", "b", "c"]) gives "a, b, c". The separator belongs to the method call, not to the list, which surprises many beginners.

join() is the standard, fast way to assemble text from many pieces. It is the opposite of split().

Python
words = ["red", "green", "blue"]
print(" - ".join(words))   # red - green - blue

Try it

Python Joining with different separators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Non-strings and other iterables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
separator.join(iterable)
Name Description
separator The string inserted between items. Use "" to join without a separator.
iterable Any iterable whose items are all str: a list, tuple, set, generator, dict (keys), or another string.

Return value: a new string. The result is the empty string if the iterable is empty, and a single item comes back with no separator.

Raises: TypeError if any item is not a string, with a message such as sequence item 0: expected str instance, int found.

Usage notes

  • Convert items first. Numbers, None and other objects must be turned into strings with str(), or with a generator expression like str(n) for n in numbers.
  • Called on the separator. list.join() does not exist. Write ",".join(items).
  • Fast. join() computes the final size once, so it is much faster than += in a loop, which can copy the growing string repeatedly.
  • Iterates once. A generator is consumed. Internally, join() collects the items into a list first, so passing a list directly avoids extra work.
  • Strings are iterables. "-".join("abc") splits into characters: "a-b-c". That is occasionally useful and often a bug.
  • Dictionaries give keys. Join d.values() or formatted items() if you need more than the keys.
  • Sets have no stable order for strings between runs, so sort first when the output matters: ", ".join(sorted(tags)).
  • Bytes have their own bytes.join() that needs bytes-like items. Mixing str and bytes raises TypeError.
  • Paths. For file paths use os.path.join() or pathlib, which handle platform separators.