TypeError: can only concatenate str (not "int") to str
In this article we will learn about the error TypeError: can only concatenate str (not "int") to str.
This error generates when we try to concatenate an int value to a string. Unlike many other languages, in python, we can not directly typecast an int value to the string. If we try to do so an error TypeError: can only concatenate str (not "int") to str generates.
Let us understand it more with the help of an example.
Example:
# User inputs of name,age and location
name = input("Enter your name :")
age= int(input("Enter your age :"))
place = input("Enter your current location :")
# Printing the information
print("Hi!! i am "+name+" i am "+ age +" years old"+" and currently lives in "+place)
Output:
Enter your name : pizza man
Enter your age :22
Enter your current location : pizza box
File "code.py", line 9, in <module>
print("Hi!! I am "+name+" I am "+ age +" years old"+"and currently lives in "+place)
TypeError: can only concatenate str (not "int") to str
In line 9 of the code, we are trying to concatenate an int value i.e ‘age’ to string values. Which is not allowed in Python and thus raising the TypeError.
Solution:
The solution for the above TypeError is to convert the int value ‘age’ to a string value and then try to concatenate.
We can explicitly convert ‘int’ value to a ‘string’ value using a built-in function str( ).
str( ) converts the arguments passed into a string explicitly.
Do ‘str(age)’ instead of ‘age’ in line 9 of the code. This will convert the int value ‘age’ to string and we can perform concatenation without an issue.
Example:
# User inputs of name,age and location
name = input("Enter your name :")
age= int(input("Enter your age :"))
place = input("Enter your current location :")
# Explicit conversion of 'int' to 'string' using str( )
print("Hi!! i am "+name+" i am "+ str(age) +" years old"+" and currently lives in "+place)
Output:
Enter your name :pizza man
Enter your age :22
Enter your current location :pizza box
Hi!! i am pizza man i am 22 years old and currently lives in pizza box