Python TypeError: can only concatenate str (not “int”) to str

Python TypeError: can only concatenate str (not “int”) to str

This exception “Python TypeError: can only concatenate str (not “int”) to str” occurs when we try to concatenate a string value and an integer value.

Let us recreate this exception by trying to concatenate a string value and an integer value.

Python Program

string_value = "Hello World"
int_value = 123456

# Concantenate string and integer
result = string_value + int_value

# Print resulting string
print(result)
Run Code Copy

Output

Traceback (most recent call last):
  File "/Users/pythonexamples_org/workspace/main.py", line 5, in <module>
    result = string_value + int_value
             ~~~~~~~~~~~~~^~~~~~~~~~~
TypeError: can only concatenate str (not "int") to str

Solution

What we are trying to do is concatenate a string value and an integer value. And Python interpreter is saying that we can only concatenate a string to another string. Therefore, we have to convert the given integer value into a string value, and then concatenate with the other string.

The above solution is implemented with the previous Python program. We converted the int_value to a string and then concatenated with the string_value. To convert an integer value to string value, we have used str() built-in function.

Python Program

string_value = "Hello World"
int_value = 123456

# Concantenate string and integer
result = string_value + str(int_value)

# Print resulting string
print(result)
Run Code Copy

Output

Hello World123456

That’s it! This is how we resolve the Python exception “TypeError: can only concatenate str (not “int”) to str”.

Summary

In this tutorial, we solved the exception “Python TypeError: can only concatenate str (not “int”) to str” by converting the integer value to a string value, and the doing the concatenation.

Related Tutorials

Code copied to clipboard successfully 👍