How to Concatenate a List of Strings into a Single String in Python

Created
Modified

Using str.join Function

The str.join() method returns a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method. For example,

#!/usr/bin/python3

s = '-'.join(["a", "c", "b"])
print(s)
a-c-b

.join is faster because it allocates memory only once. Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.

See the following example:

#!/usr/bin/python3

a = "123456"
s = ','.join(a).join(("(",")"))
print(s)
(1,2,3,4,5,6)

Related Tags