join() glues many strings into one string. You call it on the separator, and pass an iterable such as a list or a tuple: ", ".join(["a", "b"]) is "a, b". The separator goes only between the items, never at the ends.
It is the opposite of split(). Every item must be a string, or Python raises TypeError. Using an empty separator, "".join(items), simply glues the items together. The method returns a new string.
separator.join() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Call it on the separator, and pass an iterable of strings.
python
text = separator.join(iterable)
Call
What it does
", ".join(["a", "b", "c"])
Returns 'a, b, c'. The separator goes between the items.
"-".join("abc")
Returns 'a-b-c'. A string is an iterable of characters, so each character is joined.
",".join([1, 2])
Raises TypeError. The items are numbers, not strings.
To break a string apart again use split(). To swap text inside a string use replace(), and to build text from values use format().
Library declarations
python
str.join(iterable) -> str
# returns: a new string
# raises: TypeError if an item is not a string
Parameters
Parameter
Description
iterable
Required. A list, tuple, set, generator, or any other iterable whose items are all strings. For a dictionary, the keys are joined.
Return Value
Return Value
Description
str
A new string with all the items and the separator between each pair. An empty iterable gives an empty string, and one item is returned as it is.
Python Examples
Example 1 — Join Words in Different Ways
Join the same list with a space, a hyphen, nothing, and a comma.