Python String join()

The join() is a string method which returns a string concatenated with the elements of an iterable.

The join() method provides a flexible way to concatenate string. It concatenates each element of an iterable (such as list, string and tuple) to the string and returns the concatenated string.

The syntax of join() is:

string.join(iterable)

join() Parameters

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

Some of the example of iterables are:


Return Value from join()

The join() method returns a string concatenated with the elements of an iterable.

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


Example 1: How join() method works?

numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))

numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))

s1 = 'abc'
s2 = '123'

""" Each character of s2 is concatenated to the front of s1""" 
print('s1.join(s2):', s1.join(s2))

""" Each character of s1 is concatenated to the front of s2""" 
print('s2.join(s1):', s2.join(s1))

When you run the program, the output will be:

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

Example 2: How join() method works for sets?

test =  {'2', '1', '3'}
s = ', '
print(s.join(test))

test = {'Python', 'Java', 'Ruby'}
s = '->->'
print(s.join(test))

When you run the program, the output will be:

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

Note: A set is an unordered collection of items, and you may get different output.


Example 3: How join() method works for dictionaries?

test =  {'mat': 1, 'that': 2}
s = '->'
print(s.join(test))

test =  {1:'mat', 2:'that'}
s = ', '

# this gives error
print(s.join(test))

When you run the program, the output will be:

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

The join() method tries to concatenate the key (not value) of the dictionary to the string. If the key of the string is not a string, it raises TypeError exception.