Software Development

How do I resolve the TypeError unsupported operand type(s) for -: 'str' and 'str' in Python?

KA Asked by Karen White · 12-10-2024
0 upvotes 14,327 views 0 comments
The question

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

0
NA
Answered on 15-10-2024

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.

0
MA
Answered on 16-10-2024

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?

GE 18-10-2024

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?

0
BE
Answered on 20-10-2024

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.

KA 22-10-2024

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.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session