Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Python print format statement return different results. Why?

Python 2.7.5+

The new style '{X.Yf}'.format(num) doesn't seem to act like the old style '%X.Yf'%(num). Can someone explain?

>>> '%8.3f' % (0.98567)
'   0.986'
>>> '%8.3f' % (1.98567)
'   1.986'

>>> '{num:8.3}'.format(num=0.98567)
'   0.986'
>>> '{num:8.3}'.format(num=1.98567)
'    1.99'

Note how the old style displays 3 digits after the decimal, but the new style sometimes prints 2 and sometimes 3. Am I making some silly mistake?

like image 628
RonJohn Avatar asked Jun 19 '26 13:06

RonJohn


1 Answers

Use f in the new format too:

>>> '{num:8.3f}'.format(num=1.98567)
'   1.986'

Without the format type, the default is g, and the precision is interpreted as the total number of digits (not counting a 0 before the decimal). With a 1 before the declimal point, only 2 digits are shown after it.

You'd see the same output with the old string formatting if you used g instead of f:

>>> '%8.3g' % (1.98567)
'    1.99'
like image 181
Martijn Pieters Avatar answered Jun 21 '26 03:06

Martijn Pieters