Can we concatenate multiple strings at once?

Question

In Python, can we concatenate multiple strings at once, as in, in a single statement?

Answer

String concatenation is not limited to only adding two strings per statement. In a single statement, you can concatenate multiple strings at once.

When concatenating many strings, however, you may have to consider that spaces are not added automatically.

Example

string1 = "Strings "
string2 = "are "
string3 = "fun"
string4 = "!"

# Concatenating multiple strings
string1 += string2 + string3 + string4

print(string1) # Strings are fun!
5 Likes

they aren’t another way to concatenate in python without using “+”?

Previous to version 3.6 we had % and str.format(). A string can be assigned from a format.

>>> wild = 'fox'
>>> tame = 'dog'
>>> my_string = "A quick brown {} jumps over the lazy {}".format(wild, tame)
>>> my_string
'A quick brown fox jumps over the lazy dog'
>>> other_string = "A quick brown %s jumps over the lazy %s" % (wild, tame)
>>> other_string
'A quick brown fox jumps over the lazy dog'
>>> 

Python 3.6 and newer have f-strings

>>> f_string = f"A quick brown {wild} jumps over the lazy {tame}"
>>> f_string
'A quick brown fox jumps over the lazy dog'
>>> 

Note how f-strings use direct interpolation. The other two use placeholders. Check with pyformat for more information.

15 Likes

Great answer, thanks!

1 Like