Join our newsletter for the latest updates.

Python String join()

In this tutorial, we will learn about the Python String join() method with the help of examples.

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


text = ['Python', 'is', 'a', 'fun', 'programming', 'language']

# join elements of text with space print(' '.join(text))
# Output: Python is a fun programming language

Syntax of String join()

The syntax of the join() method is:


joint() 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() method

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

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

Example 1: Working of the join() method

# .join() with lists
numList = ['1', '2', '3', '4']
separator = ', '
# .join() with tuples numTuple = ('1', '2', '3', '4')
s1 = 'abc' s2 = '123' # each element of s2 is separated by s1 # '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2 # 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):', s2.join(s1))


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

Example 2: The join() method with sets

# .join() with sets
test = {'2', '1', '3'}
s = ', '
test = {'Python', 'Java', 'Ruby'} s = '->->'


2, 3, 1

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

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

# joins the keys only
test = {1: 'mat', 2: 'that'} s = ', ' # this gives error since key isn't string


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 a TypeError exception.

Did you find this article helpful?