Error messages!


4 posts
by Stevec76 » Thu Dec 20, 2012 9:02 pm
I'm still learning python and can't work out what where and this error means. I keep getting this message

Type error: bad operand type for unary +: 'str'

What I would like is some advice and why this error comes up rather than a re-written code that works.

As I said I'm a new learner and would like the reason behind this error.

Thank you in advance.
Posts: 4
Joined: Mon Nov 12, 2012 9:37 pm
by rgh » Thu Dec 20, 2012 9:24 pm
I don't know much python, but maybe it is to do with you putting numeric values inside quotes. At least, below +b is an error because b is a string, but +c isn't because c is a number:

Code: Select all
richard@bugsy:~$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="foo"
>>> b="7"
>>> c=8
>>> z=+a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
>>> z=+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
>>> z=+c
>>>
Posts: 220
Joined: Fri Nov 25, 2011 3:53 pm
by billio » Fri Dec 21, 2012 10:21 am
To put the matter simply, a "positive" string doesn't make sense.

When using "+ something", the + is a unary operator, i.e. it operates on only a single operand (the "something" bit). The error message is telling you that an operand of type str (that is, the type is a string) is an inappropriate operand for this operator.
Posts: 55
Joined: Thu Dec 15, 2011 8:25 am
by phbcanada » Sun Dec 23, 2012 1:28 pm
Yes, basically it means you're trying to do math with a string. If you post some of your code perhaps someone can make more specific suggestions.
If you're trying to create a string from numbers try something like:
Code: Select all
result = str(number) + myString

If you're trying to create a number from a string then try something like:
Code: Select all
integer = number + int(myString)
real = number + float(myString)
User avatar
Posts: 13
Joined: Tue Dec 11, 2012 1:16 pm