Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: unsupported operand type(s) for -: 'str' and 'str'"
occurs when we try to use the subtraction -
operator with two strings. To
solve the error, convert the strings to int
or float
values, e.g.
int(my_str_1) - int(my_str_2)
.
Here is an example of how the error occurs.
my_str_1 = '50' my_str_2 = '20' # ⛔️ TypeError: unsupported operand type(s) for -: 'str' and 'str' result = my_str_1 - my_str_2
We are trying to use the subtraction operator with two values of type string.
To solve the error, we have to convert the strings to numbers (e.g. integers or floats).
my_str_1 = '50' my_str_2 = '20' result = int(my_str_1) - int(my_str_2) print(result) # 👉️ 30
We used the int()
class to convert the strings to integers before using the
subtraction operator.
input()
built-in function, all of the values the user enters get converted to strings (even numeric values).If you have floats wrapped in strings, use the float()
class instead.
my_str_1 = '50' my_str_2 = '20' result = float(my_str_1) - float(my_str_2) 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.
my_str_1 = 'a 5 b 0' my_num_1 = int(''.join(filter(str.isdigit, my_str_1))) print(my_num_1) # 👉️ 50 my_str_2 = '20' result = my_num_1 - int(my_str_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.
int()
class to get an integer value.If you aren't sure what type a variable stores, use the built-in type()
class.
my_str_1 = '50' print(type(my_str_1)) # 👉️ <class 'str'> print(isinstance(my_str_1, str)) # 👉️ True my_int_1 = 20 print(type(my_int_1)) # 👉️ <class 'int'> print(isinstance(my_int_1, 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.