Python String join() Method

Joins all items in an iterable into a single string

Usage

The join() method joins all items in an iterable into a single string. Call this method on a string you want to use as a delimiter like comma, space etc.

If there are any non-string values in iterable, a TypeError will be raised.

Syntax

string.join(iterable)

Python string join() method parameters
ParameterConditionDescription
iterableRequiredAny iterable (like list, tuple, dictionary etc.) whose items are strings

Return Value

The method returns the string obtained by concatenating the items of an iterable.

Basic Examples

# Join all items in a list with comma
L = ['red', 'green', 'blue']
x = ','.join(L)
print(x)
# Prints red,green,blue
# Join list items with space
L = ['The', 'World', 'is', 'Beautiful']
x = ' '.join(L)
print(x)
# Prints The World is Beautiful
# Join list items with newline
L = ['First Line', 'Second Line']
x = '\n'.join(L)
print(x)
# First Line
# Second Line

A delimiter can contain multiple characters.

L = ['the beginning', 'the end', 'the beginning']
x = ' is '.join(L)
print(x)
# Prints the beginning is the end is the beginning

join() on Iterable of Size 1

join() method is smart enough to insert the delimiter in between the strings rather than just adding at the end of every string. So, if you pass an iterable of size 1, you won’t see the delimiter.

L = ['red']
x = ','.join(L)
print(x)
# Prints red

Join a List of Integers

If there are any non-string values in iterable, a TypeError will be raised.

L = [1, 2, 3, 4, 5, 6]
x = ','.join(L)
print(x)
# Triggers TypeError: sequence item 0: expected string, int found

To avoid such exception, you need to convert each item in a list to string. The list comprehension makes this especially convenient.

L = [1, 2, 3, 4, 5, 6]
x = ','.join(str(val) for val in L)
print(x)
# Prints 1,2,3,4,5,6

join() on Dictionary

When you use a dictionary as an iterable, all dictionary keys are joined by default.

L = {'name':'Bob', 'city':'seattle'}
x = ','.join(L)
print(x)
# Prints city,name

To join all values, call values() method on dictionary and pass it as an iterable.

L = {'name':'Bob', 'city':'seattle'}
x = ','.join(L.values())
print(x)
# Prints seattle,Bob

To join all keys and values, use join() method with list comprehension.

L = {'name':'Bob', 'city':'seattle'}
x = ','.join('='.join((key,val)) for (key,val) in L.items())
print(x)
# Prints city=seattle,name=Bob

join() vs Concatenation operator +

Concatenation operator + is perfectly fine solution to join two strings. But if you need to join more strings, it is convenient to use join() method.

# concatenation operator
x = 'aaa' + 'bbb'
print(x)
# Prints aaabbb

# join() method
x = ''.join(['aaa','bbb'])
print(x)
# Prints aaabbb