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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

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

The Python "TypeError: unsupported operand type(s) for -: 'str' and 'int'" occurs when we try to use the subtraction - operator with a string and a number. To solve the error, convert the string to an int or a float, e.g. int(my_str) - my_num.

typeerror unsupported operand type for minus str and int

Here is an example of how the error occurs.

main.py
my_str = '40' my_num = 10 # ⛔️ TypeError: unsupported operand type(s) for -: 'str' and 'int' result = my_str - my_num

We are trying to use the subtraction - operator with a string and a number.

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

main.py
my_str = '40' my_num = 10 result = int(my_str) - my_num print(result) # 👉️ 30

We used the int() class to convert the string to an integer before using the subtraction 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_str = '40' my_num = 10 result = float(my_str) - my_num print(result) # 👉️ 30.0

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_str = 'a40b' my_num_1 = int(''.join(filter(str.isdigit, my_str))) print(my_num_1) # 👉️ 40 my_num_2 = 10 result = my_num_1 - my_num_2 print(result) # 👉️ 30

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_str = '40' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_int = 10 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ 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.