Python 3 concatenate string 7 examples

Several ways to concatenate strings in python:

  • string concatenate by +
  • +=
  • .join
  • concatenate string and integer
  • concatenate two integers
  • errors

Python concatenate by +

The simplest and the most easy to read concatenation is by using plus operator. The other advantages are that is fast and intuitive. The + operator behaves like real plus operator for strings.

text1 = 'I\'m a '
text2 = 'string'
text = text1 + text2

print(text)

result:

I'm a string

Note: In case of different types - for examples string and integer - you will get error:

TypeError: cannot concatenate 'str' and 'int' objects

Python concatenate by +=

The += operator is similar to the +. This one reminds more to append. You don't need third string in order to concatenate two strings.

text1 = 'I\'m a '
text2 = 'string'
text1 += text2

print(text1)

result:

I'm a string

Python concatenate by join

If you want to use a method for concatenation in python you can use: join. You need to pass all strings as iterable:

  • [str1, str2]
  • (str1, str2, str3)

The output should be assign to new variable.

str1 = "test "
str2 = "join "
str3 = ''.join([str1, str2])
str4 = ''.join((str1, str2, str3))
print(str3)
print(str4)

result:

test join
test join test join

Python concatenate string and int

If you want to do concatenation of string and integer in python you need to case the integer to string by using str function:

number = 5
text = 'I\'m a string'
numberString = text + str(number)

print(numberString)

result:

I'm a string5

Python concatenate number stored as string

Numbers stored as strings can be converted to int and then concatenated:

number = 5
numberAsString = '5'
numberString = int(numberAsString) + number

print(numberString)

result:

10

Python concatenate two integers

In order to concatenate integers you need to cast them to string:

number = 5
number2 = 1
numberString = str(number) + str(number2)

print(numberString)

result:

51

Python concatenate characters of string with comma

Join method can be used to concatenate all characters in string with a separator:

numbers = ", ".join("123456789")
print(numbers)

result:

1, 2, 3, 4, 5, 6, 7, 8, 9

Frequent errors

If you skip the str function:

number = 5
numberAsString = '5'
numberString = text + number

You may get error:

  • python 3.X:

TypeError: Can't convert 'int' object to str implicitly

  • for python 2.X

TypeError: cannot concatenate 'str' and 'int' objects

If you try to convert non numeric to int you will get

ValueError: invalid literal for int() with base 10: 'a'