Saturday, 24 August 2013

Does operator precedence works the same way for string as for numbers?

Does operator precedence works the same way for string as for numbers?

While code golfing I stumbled on a peculiar issue
>>> print '%'+'-+'[1]+str(5)+'s'%'*'
Traceback (most recent call last):
File "<pyshell#178>", line 1, in <module>
print '%'+'-+'[1]+str(5)+'s'%'*'
TypeError: not all arguments converted during string formatting
My assumption was operator evaluation happens from left to right, but in
this particular case, it seems that even though its string operation, %
takes priority over+ and tries to evaluate 's'%'*' before the
concatenation and fails
Is this a known documented behavior, or there is something more that is
not obvious to me.

No comments:

Post a Comment