Python - unsupported operand type(s) for +:'int' and 'str'
In this tutorial, we are going to learn about how to solve the TypeError: unsupported operand type(s) for +:‘int’ and ‘str’ in Python
When we try to concatenate the integer and a string, we will get the TypeError: unsupported operand type(s) for +:‘int’ and ‘str’, because in python language we only concatenate if both values belong to the same data type.
Here is an example of how the error occurs:
price = 10 # integer
txt = ' dollars in the apple price' # string
result = price + txt
print (result)
Output:
Traceback (most recent call last):
File "main.py", line 13, in <module>
result = price + txt
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the example above, we are concatenating the integer and string using +
plus operator but both are different data types.So it throws the error in terminal.
To solve the error, convert the integer value to a string using str()
function then concatenate it using +
operator.
The str()
function takes the integer value as a argument and converts it to the string.
Here is an example:
price = 10 # integer
txt = ' dollars is the apple price' # string
result = str(price) + txt
print (result)
Output:
'10 dollars is the apple price'
We can also check what type of data that a variable holds, using the type()
function in Python.
price = 10 # integer
print(type(price)) # <class 'int'>
The type()
function returns the type of a data object.
Conclusion
The “unsupported operand type(s) for +:‘int’ and ‘str’"" error occurs, when we try to concatenate the integer and string. To solve the error, convert the integer to a string using the str()
function then add it to the string.