views:

41

answers:

2

I'm trying to represent a number with leading and trailing zeros so that the total width is 7 including the decimal point. For example, I want to represent "5" as "005.000". It seems that string formatting will let me do one or the other but not both. Here's the output I get in Ipython illustrating my problem:

In [1]: '%.3f'%5
Out[1]: '5.000'

In [2]: '%03.f'%5
Out[2]: '005'

In [3]: '%03.3f'%5
Out[3]: '5.000'

Line 1 and 2 are doing exactly what I would expect. Line 3 just ignores the fact that I want leading zeros. Any ideas? Thanks!

+6  A: 

The first number is the total number of digits, including decimal point.

>>> '%07.3f' % 5
'005.000'
nosklo
Makes sense, thanks!
Wei H
@nosklo: decimal point is a digit?
John Machin
A: 

[Edit: Gah, beaten again]

'%07.3F'%5

The first number is the total field width.

babbitt