Typeerror unsupported operand type s for str and str
Typeerror unsupported operand type s for str and str
Objects other than numbers can not be used in python substraction. The arithmetic subtract can be used only for numbers. If a number is stored as a string, it should be converted to an integer before subtracting it from each string. If you try to subtract a string to a string containing a number, the error TypeError: unsupported operand type(s) for +: ‘str’ and ‘str’ will be shown.
Exception
The error TypeError: unsupported operand type(s) for-: ‘str’ and ‘str’ will be shown as below the stack trace. The stack trace shows the line where a string is subtracted from a string that may contain valid numbers.
How to reproduce this error
If you try to subtract a string from another string containing a number, the error TypeError: unsupported operand type(s) for-: ‘str’ and ‘str’ will be reproduced. Create two python variables. Assign variables with a string that contains a valid number. Subtract from the string to another string.
Output
Root Cause
Python does not support auto casting. The arithmetic operation subtraction can be used to subtract between two valid numbers. If a string is subtracted from another string, this error will be thrown. The string may contain a valid number. The string should be converted to integer before subtracting.
Solution 1
If you try to subtract a string from another string contains a valid number, convert the string to an integer using the built in function int(). This will resolve the error. The built in function int() converts a string contains a valid number to an integer number.
Output
Solution 2
Output
Solution 3
If the variable type is unknown, the variable type should be checked before subtracting the number to another number. The example below shows the method of verification before subtracting the numbers