How to concatenate multiple strings in python

This article describes how to concatenate strings in Python.

  • Concatenate multiple strings: +, += operator
  • Concatenate strings and numbers: +, += operator, str(), format(), f-string
  • Concatenate a list of strings into one string: join()
  • Concatenate a list of numbers into one string: join(), str()

Concatenate multiple strings: +, += operator

+ 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

+= operator

You can append another string to a string with the in-place operator, +=. The string on the right is concatenated after the string variable on the left.

s1 += s2
print(s1)
# aaabbb

If you want to add a string to the end of a string variable, use the += operator.

s = 'aaa'

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

Concatenate by writing string literals consecutively

If you write string literals consecutively, they are concatenated.

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

Even if there are multiple spaces or newlines with backslash \ (considered as continuation lines) between the strings, they are concatenated.

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

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

Using this, you can write long strings on multiple lines in the code.

  • Write a long string on multiple lines in Python

You cannot do this for string variables.

# s = s1 s2 s3
# SyntaxError: invalid syntax

Concatenate strings and numbers: +, += operator, str(), format(), f-string

The + operation between different types raises an error.

s1 = 'aaa'
s2 = 'bbb'

i = 100
f = 0.25

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

If you want to concatenate a string and a number, such as an integer int or a floating point float, convert the number to a string with str() and then use the + operator or += operator.

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

Use the format() function or the string method format() if you want to convert the number format, such as zero padding or decimal places.

  • string - Format Specification Mini-Language — Python 3.8.1 documentation

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 in 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

In Python 3.6 and later, you can also use a formatted string literal (f-string). It is even simpler than format().

  • 2. Lexical analysis - Formatted string literals — Python 3.9.4 documentation

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

Concatenate a list of strings into one string: join()

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

  • Built-in Types - str - join() — Python 3.8.1 documentation

Call the join() method from 'String to insert' and pass [List of strings].

'String to insert'.join([List of strings])

If you use an empty string '', [List of strings] is simply concatenated, and if you use a comma ,, it makes a comma-delimited string. If a newline character \n is used, a newline will be inserted for 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 other iterable objects such as tuples can be specified as arguments of join().

Use split() to split a string separated by a specific delimiter and get it as a list. See the following article for details.

  • Split strings in Python (delimiter, line break, regex, etc.)

Concatenate a list of numbers into one string: join(), str()

If you set a non-string list to join(), an error is raised.

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 (int or float) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join().

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

It can be written as a generator expression, a generator version of list comprehensions. Generator expressions are enclosed in parentheses (), but you can omit () if the generator expression is the only argument of a function or method.

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

In general, generator expressions have the advantage of reduced memory usage compared with list comprehensions. However, since join() internally converts a generator into a list, there is no advantage to using generator expressions.

  • python - List vs generator comprehension speed with join function - Stack Overflow

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

  • List comprehensions in Python

How do you concatenate 3 strings in Python?

Concatenation means joining strings together end-to-end to create a new string. To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

How do you concatenate two strings in Python?

Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.

How do I combine multiple strings into one?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do I concatenate two strings with a space in Python?

Python concatenate strings with space We can also concatenate the strings by using the space ' ' in between the two strings, and the “+” operator is used to concatenate the string with space. To get the output, I have used print(my_str).