Does operator precedence match a string like a number?

While playing golf, I came across a particular problem

>>> 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 that the operator evaluates from left to right, but in this particular case it seems that even if its string operation, % takes precedence over + and tries to evaluate 's'%'*' before concatenation and crash

This is a well-known documented behavior, or there is something more that is not obvious to me.

+4
source share
1 answer

Yes, he documented here .

Priority is consistent throughout the language, regardless of the subject. Everything else would be terribly confusing, since it was possible to build objects using special "operator" methods - for example, for % , __mod__() - with arbitrary behavior. If objects could also define their own priority rules, debugging unexpected results would be much more difficult.

+4
source

Source: https://habr.com/ru/post/1498747/


All Articles