Summary: In this tutorial, we will learn what is join() in Python and how we can use it to join multiple strings.
What is join() in Python?
join() is a built-in string method in Python that joins the strings of an iterable such as list, set, tuple, etc into a single string.
It uses the string object on which it is invoked as the separator.
For example, in the following code, when we call join() on '#' with a list of strings as a parameter, it concatenates all the strings of the list separated by '#':
>>> l = ['pencil', 'programmer']
>>> '#'.join(l)
'pencil#programmer'
The syntax for join() method is:
string_separator.join(iterable)
join() Parameters
The join() method accepts an iterable as a parameter, joins the strings by the specified separator, and returns the concatenated string.
| Parameter | Condition | Description |
|---|---|---|
| iterable | Required | An iterable such as list, dict, set, string, tuple, etc with strings as returning elements. |
join()method joins the keys of the dictionary only if they are strings.
Examples using join()
Example 1: Join list of strings in Python
>>> l = ['www.pencilprogrammer.com', 'python-tutorials', 'join-method']
>>> separator = '/'
>>> separator.join(l)
'www.pencilprogrammer.com/python-tutorials/join-method'
Example 2: Join keys of dictionary in Python
>>> d = {'tom': 'cat', 'jerry': 'mouse'}
>>> separator = ' & '
>>> separator.join(d)
'jerry & tom'
Because the elements in the dictionary is not ordered, the join method joins the string in different order.
Example 3: Concatenate characters of the string separated by the given string.
>>> name = 'Rock'
>>> separator = '-'
>>> separator.join(name)
'R-o-c-k'
In summary, the string.join() method in Python concatenates the strings of an iterable by a separator into a single string object.