String Concatenation in Python

Concatenation is a method of joining strings together to form a new string altogether.

The following are the methods to perform String Concatenation in Python:

  1. By using + operator
  2. By using join() method
  3. By using % operator
  4. By using format() function
  5. By Literal String Interpolation
  6. By using StringIO from IO Module
  7. By using += concatenate operator

1. String Concatenation using + Operator

Syntax: string1 + string2

str1 = 'Safa'
str2 = 'Mulani'

result = str1 + str2


Output: SafaMulani

2. Python String Concatenation using join() Method

Syntax: join(string1,string2)

str1 = 'Safa'
str2 = 'Mulani'

print(" ".join([str1, str2]))

Output: Safa Mulani

3. String Concatenation using the % operator

Syntax: %(string1,string2)

str1 = 'Safa'
str2 = 'Mulani'
result = "%s %s" % (str1, str2)
print('Concatenated String =', result)

Output: Concatenated String = Safa Mulani

4. String Concatenation using format() function

Syntax: format(string1,string2)

str1 = 'Safa'
str2 = 'Mulani'
res = "{} {}".format(str1, str2)
print('Concatenated String=', res)

Output: Concatenated String= Safa Mulani  

5. String Concatenation using Literal String Interpolation

Python 3.6+ versions allow us to use f-string for string concatenation introduced in Literal String Interpolation.

Syntax: f'{string1} {string2}’

str1 = 'Safa'
str2 = 'Mulani'
res = f'{str1} {str2}'
print('Concatenated String =', res)

Output: Concatenated String = Safa Mulani

6. Concatenate Strings using StringIO from IO Module

from io import StringIO
result = StringIO()
result.write('Safa ')
result.write('Mulani ')
result.write('Engineering ')

Output: Safa Mulani Engineering

7. Using += concatenate operator

Syntax: string1 += string2

str1 = 'Safa '
str2 = 'Mulani'
str1 += str2

Output: Safa Mulani