Concatenate strings in Python (+ operator, join, etc.)

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 string literals ('...' or "...") and string variables with 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 with the += operator. The string on the right is concatenated after 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 there are multiple spaces, newlines, or backslashes \ (used as continuation lines) between the strings, they will still be concatenated.

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

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

This approach can be handy when you need to write long strings over 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()

The + operation 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 and a number, such as an integer (int) or a floating point number (float), you first need to convert the number to a string using str(). Then, you can use the + or += operator to concatenate.

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

Of course, it is also possible to embed the value of a variable directly into a string without specifying the 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 with 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 [LIST_OF_STRINGS], while using a comma (,) will create a comma-delimited 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 take other iterable objects, like tuples, as its argument.

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 list comprehensions 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 not significant with join(), which internally converts a generator to a list.

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

Related Categories

Related Articles