Python is doing string multiplication where I would expect it to do numeric multiplication, and I don't know why.
>>> print('%d' % 2 * 4)
2222
>>> print('%d' % (2 * 4))
8
Even forcing the type to integer does nothing. (I realize this is redundant, but it's an idiot-check for me:
>>> print('%d' % int(2) * int(4))
2222
Obviously I solved my problem (adding the parenthesis does it) but what's going on here? If this is just a quirk I have to remember, that's fine, but I'd rather understand the logic behind this.
You are experiencing operator precedence.
In python %
has the same precedence as *
so they group left to right.
So,
print('%d' % 2 * 4)
is the same as,
print( ('%d' % 2) * 4)
Here is the python operator precedence table.
Since it is difficult to remember operator precedence rules, and the rules can be subtle, it is often best to simply use explicit parenthesis when chaining multiple operators in an expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With