Python String join()

The string join() method returns a string by joining all the elements of an iterable (list, string, tuple), separated by the given separator.

Example


Syntax of String join()

The syntax of the join() method is:

string.join(iterable)

join() Parameters

The join() method takes an iterable (objects capable of returning its members one at a time) as its parameter.

Some of the example of iterables are:

Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.


Return Value from join()

The join() method returns a string created by joining the elements of an iterable by the given string separator.

If the iterable contains any non-string values, it raises the TypeError exception.


Example 1: Working of the join() method

Output

1, 2, 3, 4
1, 2, 3, 4
s1.join(s2): 1abc2abc3
s2.join(s1): a123b123c

Example 2: The join() method with sets

Output

2, 3, 1
Python->->Ruby->->Java

Note: A set is an unordered collection of items, so you may get different output (order is random).


Example 3: The join() method with dictionaries

Output

mat->that
Traceback (most recent call last):
  File "...", line 12, in <module>
TypeError: sequence item 0: expected str instance, int found

The join() method tries to join the keys (not values) of the dictionary with the string separator.

Note: If the key of the string is not a string, it raises the TypeError exception.