Bug or intended behavior?

Irmen de Jong irmen.NOSPAM at xs4all.nl
Fri Jun 2 13:31:44 EDT 2017


On 2-6-2017 19:17, sean.dizazzo at gmail.com wrote:
> Can someone please explain this to me?  Thanks in advance!
> 
> ~Sean
> 
> 
> Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) 
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> print "foo %s" % 1-2
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>>>


The % operator has higher precedence than the - operator.
See https://docs.python.org/3/reference/expressions.html#operator-precedence
So what you wrote is equivalent to:

    print ("foo %s" % 1) - 2

which means subtract the number 2 from the string "foo 1". Hence the error.

Solution is to use parentheses to make sure the things are evaluated in the order you
intended:

    print "foo %s" % (1-2)


Irmen



More information about the Python-list mailing list