In this tutorial, we will learn how to solve the Python TypeError: can only concatenate str (not “int”) to str.
[Solved] Python TypeError: can only concatenate str (not “int”) to str
As the error message says, in Python, you can only concatenate string to string. But, if you got this message, may be, you are trying to concatenate an integer to a string.
In the following example, we shall recreate the above error, and discuss on what went wrong in the eyes of Python.
site = 'www.tutorialkart.com'
year = 2020
print(string + integer)
If you run the above Python program, you will get the following output in Python terminal.
Traceback (most recent call last):
File "d:/workspace/fipics/rough.py", line 3, in <module>
print(string+integer)
TypeError: can only concatenate str (not "int") to str
The datatype of variable site is string and that of year is integer. Let us check that programmatically.
Python Program
site = 'www.tutorialkart.com'
year = 2020
print(type(site))
print(type(year))
Output
<class 'str'>
<class 'int'>
Yeah! As the Python interpreter is saying, we are trying to concatenate string and integer.
Solution
So, how do we solve this issue and print a number along with the string or concatenate the number to a string.
Convert the integer to a string using string class str().
In the following example, we shall concatenate the integer to string by converting the integer to a string.
site = 'www.tutorialkart.com'
year = 2020
print(site+str(year))
Run the above Python program, and the program shall run without any errors.
www.tutorialkart.com2020
Conclusion
Concluding this Python Tutorial, please note that Python does not allow the concatenation of string with integer. And to solve this, you may have to exclusively convert the integer to a string.