Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Khamkéo Vilaysing
The Python "TypeError: Can only concatenate str (not "numpy.int64") to str"
occurs when we try to concatenate a string and a numpy int. To solve the error,
convert the numpy int to a string, e.g. str(my_numpy_int)
to concatenate the
strings.
Here is an example of how the error occurs.
import numpy as np str_1 = 'it costs: ' num_1 = np.power(10, 3, dtype=np.int64) # ⛔️ TypeError: can only concatenate str (not "numpy.int64") to str result = str_1 + num_1
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 int to a string.
import numpy as np str_1 = 'it costs: ' num_1 = np.power(10, 3, dtype=np.int64) # 👇️ convert to str result = str_1 + str(num_1) print(result) # 👉️ 'it costs: 1000'
We passed the numpy integer 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 an integer, you need to convert the string to an integer (or float) to add the two numbers.
import numpy as np str_1 = '500' num_1 = np.power(10, 3, dtype=np.int64) result = int(str_1) + num_1 print(result) # 👉️ 1500
We passed the string to the int()
class to convert it to an integer. Note that
you can also use the float()
class if you need to convert a string to a
floating-point number.
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(10, 3, dtype=np.int64) result = f'{str_1} {num_1} usd' print(result) # 👉️ 'it costs 1000 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(10, 3, dtype=np.int64) print(type(num_1)) # 👉️ <class 'numpy.int64'> print(isinstance(num_1, np.int64)) # 👉️ 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.