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