TypeError: unsupported operand type(s) for +: int and str

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: unsupported operand type(s) for +: int and str #

The Python "TypeError: unsupported operand type(s) for +: 'int' and 'str'" occurs when we try to use the addition (+) operator with an integer and a string. To solve the error, convert the string to an integer, e.g. my_int + int(my_str).

typeerror unsupported operand type for plus int and str

Here is an example of how the error occurs.

main.py
my_int = 10 my_str = '5' # ⛔️ TypeError: unsupported operand type(s) for +: 'int' and 'str' result = my_int + my_str

We are trying to use the addition (+) operator with a number and a string.

To solve the error, we have to convert the string to a number (an int or a float).

main.py
my_int = 10 my_str = '5' result = my_int + int(my_str) print(result) # 👉️ 15

We used the int() class to convert the string to an integer before using the addition operator.

IMPORTANT: if you use the input() built-in function, all of the values the user enters get converted to strings (even numeric values).

If you have a float wrapped in a string, use the float() class instead.

main.py
my_int = 10 my_str = '5' result = my_int + float(my_str) print(result) # 👉️ 15.0

If you are trying to concatenate strings, convert the number to a string by using the str() class.

main.py
my_int = 123 my_str = 'abc' result = str(my_int) + my_str print(result) # 👉️ "123abc"

If you have a string that may also contain characters but you only need to extract an integer, use the filter() function to filter out all non-digits.

main.py
my_int_1 = 100 my_str = 'a5b0' my_int_2 = int(''.join(filter(str.isdigit, my_str))) print(my_int_2) # 👉️ 50 result = my_int_2 + my_int_1 print(result) # 👉️ 150

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

We basically check if each character in the string is a digit, return the result and join the digits into a single string before using the int() class to get an integer value.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_int = 100 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True my_str = '50' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.