One error that you might get in Python is:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
This error occurs when you try to subtract a string value from another string.
The following tutorial shows an example that causes this error and how to fix it.
How to reproduce this error
This error occurs when you put two strings as operands to the subtraction -
operator as shown below:
x = "a" - "b"
# TypeError: unsupported operand type(s) for -: 'str' and 'str'
The most common cause for this error is when you use the input()
function to ask for two numbers in Python.
Suppose you want to ask users for two numbers, then reduce the first with the second as follows:
x = input("Input the first number: ")
y = input("Input the second number: ")
z = x - y
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
z = x - y
TypeError: unsupported operand type(s) for -: 'str' and 'str'
The input()
function returns the user input as a string type. When you subtract the number y
from x
to produce z
, the error will be raised.
How to fix this error
To resolve this error, you need to convert both strings into numbers.
This can be done using the int
or float
function, depending on whether you’re processing integers or floats.
The following is an example of processing integers:
x = input("Input the first number: ")
y = input("Input the second number: ")
z = int(x) - int(y)
Or if you have floats:
x = input("Input the first number: ")
y = input("Input the second number: ")
z = float(x) - float(y)
Both integers and floats are supported by the subtraction -
operator, so you won’t raise this error.
I hope this tutorial is helpful. Happy coding! 👍