Typeerror: bad operand type for unary -: str

Are you having a hard time fixing “Typeerror: bad operand type for unary -: str”?

Don’t worry! this article will help you to fix your problem.

In this article, we will discuss “Typeerror: bad operand type for unary -: str”, give the possible causes of this error, and provide solutions to resolve the error.

So first, let us understand what this error means.

What is Typeerror: bad operand type for unary -: str?

The error message “Typeerror: bad operand type for unary -: str” means that you are trying to use the unary minus operator (“-“) with a string operand, which is not allowed.

For example:

my_string = "hello world"
negated_string = -my_string

In this example, we try to negate a string, by this python raises an error:

TypeError: bad operand type for unary -: 'str'

Because it doesn’t make sense to negate a string.

Unary minus operator

The unary minus operator is typically used for numeric values to invert their sign (e.g., -5).

However, it cannot be used with non-numeric types such as strings.

If you try to apply the unary minus operator to a string, Python will raise a TypeError indicating:

TypeError: bad operand type for unary -: str

Now we will discuss the reason why this error occurs.

Why does Typeerror: bad operand type for unary -: str occurs?

The main reason why “TypeError: bad operand type for unary -: str” occurs is when you try to apply the unary minus operator (“-“) to a string.

The unary minus operator(-) shows a negative value, and it is recommended to only be used with numerical data types such as int, float values, and complex numbers.

Just like the example below:

my_string = "Python"
negative_string = -my_string
print(negative_string)

In this example, we’re trying to negate a string (“my_string”) using the unary minus operator (“-“).

Since the unary minus operator is only defined for numeric types, Python raises an error stating:

TypeError: bad operand type for unary -: 'str'

Now let’s fix this error.

How to fix Typeerror: bad operand type for unary -: str?

Here are the different solutions to fix this error:

Solution 1:  Convert the string to a numerical value using the int() or float() function.

The main solution to fix the error is to convert the string to a number value using the int() or float() function.

Just like this:

x = "10"

x_int = int(x)

y = -x_int

print(y)

In this code, we converted the string “10” to an integer using the int() function and then used the unary minus operator(-) on the integer to show the negative value.

Output

-10

Solution 2: Convert the string to a numeric type

If you have a string that represents a numeric value, you could try converting it to a numeric type like an integer or float.

Then using the unary minus operator(-) on the numeric value.

For example:

my_string = "5"
my_number = int(my_string)
negated_number = -my_number
print(negated_number)

This code sets the variable my_string to the string “5”, and converts it to an integer using the int() function.

Then applies the unary minus operator (-) to negate the resulting integer.

Solution 3: Check the type of the operand before applying the unary minus operator.

Before applying the unary minus operator to a variable, you could check its type to make sure that it is a numeric type and not a string.

For example:

my_variable = "hello"
if isinstance(my_variable, (int, float, complex)):
    negated_number = -my_variable
    print(negated_number)
else:
    print("Cannot apply unary minus operator to non-numeric type")

In this example code checks whether the variable “my_variable” is an instance of the int, float, or complex classes.

if it is, apply the unary minus operator to negate the value.

If it is not a numeric type, it prints a message indicating:

Cannot apply unary minus operator to non-numeric type

So those are the possible solutions to the “TypeError: bad operand type for unary -: str” error.

The best solution will depend on the specific context in which the error is occurring, and what you are trying to achieve in your code.

Here are the other fixed Python errors that you can visit, you might encounter them in the future.

Conclusion

In conclusion, in this article, we discuss “TypeError: bad operand type for unary -: str”, provide its causes and give solutions that resolve the error.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

I hope this article helps you to solve your problem regarding a Typeerror stating “bad operand type for unary -: str”.

We’re happy to help you.

Happy coding! Have a Good day and God bless.

Frequently Asked Questions

What is Python TypeError and what causes it?

TypeError is raised when an operation is applied to an object of the wrong type. Common patterns: calling a non-callable object, adding incompatible types (str + int), passing the wrong number of arguments, or accessing attributes on a NoneType. Each TypeError message names the operation and expected vs actual types, the fix is almost always to convert types explicitly (int(), str()) or fix the wrong variable assignment.

How do I quickly debug a Python TypeError?

Three steps: (1) Read the full error message, it names the exact operation and types involved. (2) Print the type of every variable in that line: print(type(var1), type(var2)). (3) Check what the function expected vs what you passed. Most TypeError fixes are 1-line type casts or fixing a variable that became None unexpectedly.

Should I catch TypeError or let it propagate?

For internal code, let TypeError propagate, it’s almost always a real bug (wrong type passed). For boundary code (parsing user input, third-party API responses), catch TypeError + ValueError together: try: parsed = int(value) except (TypeError, ValueError): parsed = 0. Catching internal TypeErrors hides bugs.

How do I prevent TypeError in production?

Three patterns: (1) Use type hints (def add(a: int, b: int) -> int) and check with mypy / pyright in CI. (2) Validate inputs at boundaries (Pydantic for FastAPI, DRF serializers for Django). (3) Default values that match expected types (return 0 not None for numeric functions). Static typing catches 80% of TypeErrors before runtime.

Where can I find more TypeError fixes?

Browse the TypeError reference hub for 220+ specific TypeError fixes. For broader Python debugging, see the Python Tutorial hub. For related error types, see ValueError and AttributeError guides.

John Paul Blauro

Programmer & Technical Writer at PIES IT Solution

John Paul Blauro is a programmer and writer at PIES IT Solution, author of 55 Python error-fix tutorials at itsourcecode.com. Specializes in Python TypeError debugging (str/int type errors, unsupported operand types, iterable-related issues) and AttributeError debugging (NoneType, dict/list/series object attribute errors) for developers and BSIT students.

Expertise: Python · Python TypeError · Python AttributeError · Type Debugging · Error Handling  · View all posts by John Paul Blauro →