TypeError: bad operand type for unary ‘str’ [SOLVED]

In this article, we will provide solutions to typeError: bad operand type for unary ‘str’, example codes, and a discussion about this error.

What is unary operators?

Unary operators are operators that take only one operand. In Python, some of the commonly used unary operators include the positive and negative signs (+ and -). Then, the bitwise NOT operator (~), and the logical NOT operator (not).

These operators are often used to perform mathematical operations or to invert boolean values.

Bad operand type error

The bad operand type error occurs when the operand passed to a unary operator is of the wrong data type.

For instance, applying the logical NOT operator to a non-boolean value would result in a bad operand type error.

TypeError: bad operand type for unary ‘str’

In Python, TypeError is a common error that occurs when the data types used in an operation are not compatible.

One specific variation of this error is the “bad operand type for unary ‘str‘” error. This error indicates that the code is trying to apply a unary operator to a variable or value of the wrong data type.

Example of TypeError: bad operand type for unary ‘str’

One example of type error is TypeError: bad operand type for unary +: ‘str’ it is raised when we use the unary plus operator (+) on a string value.

The unary plus operator(+) shows a positive value, and it is recommended to only be used with numerical data types such as int and float values.

Example error program:

a = "20"
b = +a

print(b)

Result:

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

How to fix TypeError: bad operand type for unary ‘str’

Here are the solutions to fix the given TypeError: bad operand type for unary ‘str’ error above.

1. Convert a string to numerical value using int or float

The first thing we should do to fix typeError: bad operand type for unary +: ‘str’ is to convert the string to numerical value.

Example program:

sample = "2023"

sample_int = int(sample)

result = +sample_int

print(result)

Result:

2023

The code above demonstrates the conversion of string ‘2023’ into an integer using the int function. Along with it uses the unary + plus operator to show a positive value.

Primarily, that unary + operator shows the positive value of a numerical expression. Although it doesn’t perform actual mathematical operations hence it returns the numerical value as is.

2. Use concatenate + on string

This time we will use + operator on a string. It will not cause an error TypeError: bad operand type for unary ‘str’ since we use it to concatenate a string, assumingly we are not using an operator in string.

Meanwhile, if we are trying to add two numeric values but typeerror is thrown. This means one of the value is a string or behave like a string. That is why make sure to have numeric values before executing addition.

Here is the example code:

x = "20"
y = "23"

z = x + y

print(z)

Here is the output using concatenation.

2023

3. Check the type of the object before performing the operation:

You can use the type() function to check the type of the object before performing the string operation.

x = 5
if type(x) == str:
    print("x is a string")
else:
    print("x is not a string")

Output:

x is not a string

Conclusion

In conclusion, the “bad operand type for unary ‘str’” error occurs when attempting to use a unary operator on a value of the wrong data type. Understanding the causes of this error and how to properly handle string operations can help you avoid this common issue in Python.

We hope that this article has helped you resolve this error and that you can now continue working on your Python projects without any issues.

If you are finding solutions to some errors you might encounter we also have Typeerror: can’t compare offset-naive and offset-aware datetimes.

Understanding “unsupported operand type” TypeErrors

Every operator (+, -, *, /) is defined on specific type pairs. Python does NOT auto-convert types like JavaScript does. Adding an integer to a string, or comparing a list to a dict, raises TypeError.

Common triggers

  • int + str. "Age: " + 25 fails. Use f-string: f"Age: {25}".
  • str * float. "ab" * 2.5 fails. Only int multiplication is allowed on strings.
  • None arithmetic. Any arithmetic on None gives an unsupported-operand error.
  • Comparing dict to list. Python 3 raises TypeError on many cross-type comparisons (unlike Python 2).
  • Path + str. pathlib.Path + string works only with / (division operator), not +.

Diagnostic pattern

# BAD — mixing int and str
count = 5
msg = "You have " + count + " items"
# TypeError: can only concatenate str (not "int") to str

# GOOD — three modern ways
msg = f"You have {count} items"       # f-string (Python 3.6+)
msg = "You have {} items".format(count)  # .format()
msg = "You have " + str(count) + " items"  # explicit conversion

Best practices

  • Prefer f-strings. Cleaner and faster than concatenation or .format().
  • Use str() explicitly when you need a string representation of any non-string value.
  • Use Decimal for money. Mixing float and Decimal in arithmetic often causes surprises.

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.

Glay Eliver


Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame
 · View all posts by Glay Eliver →

Leave a Comment