str.join()

Joins the elements of a collection of strings into one string with a separator.

Returns
A new string.
Changes the original
No
On this page

Example

#
Python
tags = ["html", "css", "python"]
print(", ".join(tags))
print(" β†’ ".join(tags))
print("".join(["C", "o", "d", "e"]))

scores = [92, 78, 85]
print(" | ".join(str(s) for s in scores))
Resultsaved result, you can check it
html, css, python
html β†’ css β†’ python
Code
92 | 78 | 85

Definition and usage

#

The join() method is called on the separator, and takes a collection of strings as its argument: ", ".join(names) joins names with commas. This syntax looks unusual at first, but it is very practical.

All elements must be strings. Numbers need to be converted first, most conveniently with a generator: ", ".join(str(n) for n in numbers).

This is also the fastest way to build long strings out of many parts. Repeatedly adding strings with + in a loop is much slower.

Syntax

#
Syntax
separator.join(iterable)

Parameters

#
  • iterable

    a collection of strings

    The elements to join.

Good practices

#
  • When joining numbers, convert them to text first: ", ".join(map(str, numbers)).
  • In an English sentence, join everything except the last item, then add the word and before it (for example: HTML, CSS, and Python).

Related entries

#

Spotted a mistake or missing an example? Write to us.