Can only concatenate str (not "numpy.int64") to str

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

Can only concatenate str (not "numpy.int64") to str #

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.

typeerror can only concatenate str not numpy int64 to str

Here is an example of how the error occurs.

main.py
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
We tried to use the addition (+) operator to concatenate a string and an integer which caused the error.

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.

main.py
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.

main.py
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.

IMPORTANT: if you use the 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.

main.py
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'
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with 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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.