Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: can only concatenate str (not "numpy.float64") to str"
occurs when we try to concatenate a string and a numpy float. To solve the
error, convert the numpy float to a string, e.g. str(my_float)
to concatenate
the strings.
Here is an example of how the error occurs.
import numpy as np my_float = np.power(13.3, 3, dtype=np.float64) # ⛔️ TypeError: can only concatenate str (not "numpy.float64") to str result = 'It costs: ' + my_float
The values on the left and right-hand sides need to be of compatible types.
One way to solve the error is to convert the numpy float to a string.
import numpy as np my_float = np.power(13.3, 3, dtype=np.float64) result = 'It costs: ' + str(my_float) print(result) # 👉 It costs: 2352.637
We passed the numpy floating-point number to the str()
class and converted it
to a string before concatenating the two strings.
If you have a number that is wrapped in a string and a float, you need to convert the string to a float (or an integer) to add the two numbers.
import numpy as np my_float = np.power(13.3, 3, dtype=np.float64) result = float('10.3') + my_float # 👇️ or use np.float64 # result = np.float64('10.3') + my_float print(result) # 👉 2362.9370000000004
We passed the string to the float()
class to convert it to a floating-point
number. Note that you can also use the int()
class if you need to convert a
string to an integer.
input()
built-in function, all of the values the user enters get converted to strings (even numeric values).An alternative to concatenating strings with the addition (+) operator is to use a formatted string literal.
import numpy as np str_1 = 'it costs: ' num_1 = np.power(13.3, 3, dtype=np.float64) result = f'{str_1} {num_1} usd' print(result) # 👉️ 'it costs: 2352.637 usd'
f
.Make sure to wrap expressions in curly braces - {expression}
.
If you aren't sure what type a variable stores, use the built-in type()
class.
import numpy as np str_1 = 'it costs: ' print(type(str_1)) # 👉️ <class 'str'> print(isinstance(str_1, str)) # 👉️ True num_1 = np.power(13.3, 3, dtype=np.float64) print(type(num_1)) # 👉️ <class 'numpy.float64'> print(isinstance(num_1, np.float64)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.