When you observe unexpected behavior, start the analysis, diverting it to the simplest possible case. A simple case will be easier to learn and understand.
Unexpected behavior:
>>> 'hello %s' % 3 * 2 'hello 3hello 3'
(You expected 'hello 6' )
We believe that Python should interpret the command as 'hello 3' * 2 , not 'hello %d' % 6 . We are trying to force the second interpretation with parentheses
>>> "hello %s" % (3*2) 'hello 6'
Eureka!
We have demonstrated that the % line format operator has greater or equal priority than multiplication. We check the Python documentation - yes, this confirms this http://docs.python.org/reference/expressions.html#summary
To confirm that priority is equal, we can try it the other way around:
>>> "%d,"*2%(1,2) '1,2,'
Having seen that the comma (,) is duplicated, we believe that the multiplication "%d," * 2 was performed before formatting the string % . If multiplication can precede string formatting, and string formatting precedes multiplication, they should be equal in priority.
Colonel panic
source share