I am trying to perform some basic data manipulation where I subtract one value from another, but I keep getting "TypeError: unsupported operand type(s) for -: 'str' and 'str'". It seems Python thinks my numerical data is actually text. I am pulling this data from a CSV file using a standard reader. How can I properly convert these variables so that I can perform mathematical subtractions without the interpreter throwing this type error?
3 answers
This error occurs because Python does not support the subtraction operator for string objects. Even if your strings look like numbers (e.g., "10"), they are treated as text. You must explicitly cast them to a numerical type like int() or float() before performing the operation. For example, instead of result = var1 - var2, you should use result = int(var1) - int(var2). If you are working with data from a CSV, it is a very common scenario as many readers import everything as a string by default. Always ensure you handle potential ValueError exceptions in case a string cannot be converted to a number.
Are you using the Pandas library to read your CSV file, or are you using the built-in CSV module, as Pandas usually attempts to infer the correct data types automatically?
You just need to wrap your variables in float() before the minus sign. Python is very strict about not letting you "subtract" text from other text.
I agree with Betty. It's a classic beginner mistake to forget that input from files or users is always a string. Explicitly converting your types is the most straightforward fix for this specific TypeError.
Thanks for the follow-up, Mark. I am actually using the standard csv module right now. If I switch to Pandas, will I still need to manually wrap my columns in a conversion function like pd.to_numeric(), or is there a specific argument I can pass during the read_csv call to ensure these columns are treated as floats from the very beginning of the process?