Concatenate Strings in Python: +, +=, join(), and more

Modified: | Tags: Python, String

This article explains how to concatenate strings or join a list of strings in Python.

Concatenate Strings: +, +=

The + Operator

You can concatenate both string literals ('...' or "...") and string variables using the + operator.

s = 'aaa' + 'bbb' + 'ccc'
print(s)
# aaabbbccc

s1 = 'aaa'
s2 = 'bbb'
s3 = 'ccc'

s = s1 + s2 + s3
print(s)
# aaabbbccc

s = s1 + s2 + s3 + 'ddd'
print(s)
# aaabbbcccddd

The += Operator

You can append a string to an existing string variable using the += operator. The string on the right is added to the end of the string variable on the left.

s1 = 'aaa'
s2 = 'bbb'

s1 += s2
print(s1)
# aaabbb

s = 'aaa'

s += 'xxx'
print(s)
# aaaxxx

Concatenate Consecutive String Literals

If you write string literals consecutively, they are automatically concatenated.

s = 'aaa''bbb''ccc'
print(s)
# aaabbbccc

Even if you insert multiple spaces, newlines, or continuation backslashes (\) between the string literals, they will still be concatenated.

s = 'aaa'  'bbb'    'ccc'
print(s)
# aaabbbccc

s = 'aaa'\
    'bbb'\
    'ccc'
print(s)
# aaabbbccc

This approach is useful when writing long strings across multiple lines of code.

Note that this automatic concatenation cannot be applied to string variables.

# s = s1 s2 s3
# SyntaxError: invalid syntax

Concatenate Strings and Numbers: +, +=, str(), format(), f-strings

The + and += Operators and str()

Using the + operator between different types results in an error.

s1 = 'aaa'
s2 = 'bbb'

i = 100
f = 0.25

# s = s1 + i
# TypeError: must be str, not int

To concatenate a string with a number, such as an integer (int) or a floating-point number (float), you need to first convert the number to a string using str(). Then, you can use the + or += operator to concatenate them.

s = s1 + '_' + str(i) + '_' + s2 + '_' + str(f)
print(s)
# aaa_100_bbb_0.25

format() and f-strings

If you need to adjust the format, such as adding zero-padding or specifying decimal places, the format() function or the str.format() method can be used.

s1 = 'aaa'
s2 = 'bbb'

i = 100
f = 0.25

s = s1 + '_' + format(i, '05') + '_' + s2 + '_' + format(f, '.5f')
print(s)
# aaa_00100_bbb_0.25000

s = '{}_{:05}_{}_{:.5f}'.format(s1, i, s2, f)
print(s)
# aaa_00100_bbb_0.25000

You can also embed variable values directly into a string without specifying a format, which is simpler than using the + operator.

s = '{}_{}_{}_{}'.format(s1, i, s2, f)
print(s)
# aaa_100_bbb_0.25

For more information about format() and str.format(), including format specification strings, see the following article.

In Python 3.6 or later, you can also use f-strings for a more concise syntax.

s = f'{s1}_{i:05}_{s2}_{f:.5f}'
print(s)
# aaa_00100_bbb_0.25000

s = f'{s1}_{i}_{s2}_{f}'
print(s)
# aaa_100_bbb_0.25

Join a List of Strings into One String: join()

You can concatenate a list of strings into a single string using the string method join().

Call the join() method on the string you wish to insert between the elements (e.g., 'STRING_TO_INSERT') and pass a list of strings (e.g., [LIST_OF_STRINGS]).

'STRING_TO_INSERT'.join([LIST_OF_STRINGS])

Using an empty string ('') will simply concatenate the list elements, while using a comma (,) will create a comma-separated string. If a newline character \n is used, a newline will be inserted between each string.

l = ['aaa', 'bbb', 'ccc']

s = ''.join(l)
print(s)
# aaabbbccc

s = ','.join(l)
print(s)
# aaa,bbb,ccc

s = '-'.join(l)
print(s)
# aaa-bbb-ccc

s = '\n'.join(l)
print(s)
# aaa
# bbb
# ccc

Note that join() can also accept other iterable objects, such as tuples.

Use split() to split a string separated by a specific delimiter into a list. See the following article for details.

Join a List of Numbers into One String: join(), str()

Using join() with a non-string list raises an error.

l = [0, 1, 2]

# s = '-'.join(l)
# TypeError: sequence item 0: expected str instance, int found

If you want to concatenate a list of numbers, such as int or float, into a single string, you can convert the numbers to strings using list comprehension with str(), and then concatenate them using join().

s = '-'.join([str(n) for n in l])
print(s)
# 0-1-2

You can also use a generator expression, which is similar to a list comprehension but creates a generator instead. Generator expressions are enclosed in parentheses (). However, if the generator expression is the only argument to a function or method, you can omit the parentheses.

s = '-'.join((str(n) for n in l))
print(s)
# 0-1-2

s = '-'.join(str(n) for n in l)
print(s)
# 0-1-2

While generator expressions generally use less memory than list comprehensions, this advantage is negligible when using join(), which internally converts the generator to a list.

See the following article for details on list comprehensions and generator expressions.

Related Categories

Related Articles