Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String Formatting And String Multiplication Oddity

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.

like image 790
Schof Avatar asked Dec 10 '22 19:12

Schof


1 Answers

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.

like image 101
Karl Voigtland Avatar answered Feb 19 '23 15:02

Karl Voigtland