String join() in Python

thumbnail

In this tutorial, you will learn to do string concatination using string method join() in python. The join() is a string method which returns a string concatenated with the elements of an iterable, such as List, Tuple, String, Dictionary and Set. It can concatenated each element of an iterable to the string and returns the result or concatenated string.

The syntax of join() is present at below:

string.join(iterable)

Parameters

Like I said before, the join() method takes an iterable for the input. The objects that capable of returning its members one at a time.

Some of the example of iterable are:

  1. File objects and objects you define with an __iter__() or __getitem()__method
  2. Native datatypes(such as List, Tuple, String, Dictionary, and Set)

Return value

The join() method returns a string concatenated with the elements of an iterable. If the iterable contains any non-string, it raises a TypeError exception.

Example 1: Join() method in List and Tuple

# Example of join() method in list
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))

# Example of join() method in tuple
numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))

When you run the program, the ouput will be:

1, 2, 3, 4
1, 2, 3, 4

Example 2: Join() method for Sets

# Example of join() method for Sets
test1 =  {'3', '2', '1'}
s = ' -> '
print(s.join(test1))

test2 = {'Wakeup', 'Work', 'Sleep'}
s = ' -> '
print(s.join(test2))

The output will be:

2 -> 3 -> 1
Work -> Sleep -> Wakeup

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

Example 3: Join() method for dictionaries

# Example of join() method for Dictionaries
test =  {'this': 1, 'that': 2}
s = '->'
print(s.join(test))

The output will be:

this->that

But if you use the key of the string is not a string, you will get TypeError exception because join() method tries to concatenate the key (not value) of the dictionary to the string.

# Example of join() method for Dictionaries
test =  {1:'this', 2:'that'}
s = ', '

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

The TypeError exception you will get is like this:

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

Read another Python tutorial in this Website.

Back To Top