I want to print some integers in a zero padded fashion, eg. :
>>> print("Testing %04i" % 1)
Testing 0001
but the padding needs to be dynamic eg. sometimes %05i, %02i or some
other padding amount. But I can't insert a variable into the format
specification to achieve the desirable padding.
I would be much obliged if someone can give me some tips on how to
achieve a variably pad a number.
Cheers,
Fred.
Thanks,
Fred.
:)
('%%0%dd' % (pads,)) % (n,)
Probably be good to wrap it in a function. It looks kind of obscure as it
is.
Mel.
http://docs.python.org/library/stdtypes.html#str.zfill
Cheers,
Chris
Something like this works:
>>> for ii in ((3,12),(4,140),(5,123)):
... print ("Testing %%%02ii" % ii[0]) % ii[1]
...
Testing 012
Testing 0140
Testing 00123
Emile
--> width = 3
--> print("Testing %0*i" % (width, 1))
Testing 001
--> width = 7
--> print("Testing %0*i" % (width, 1))
Testing 0000001
The '*' acts as a place holder for the width argument.
~Ethan~
>>>> b='04'
>>>> a="testing %"+b+"i"
>>>> print(a % 1)
> testing 0001
kind regards,
m harris
> The '*' acts as a place holder for the width argument.
very nice...
Would get rather pretty (read: ugly and impossible to read) if you
wanted to put a literal percent sign in front of the number.
:)
Chris Angelico
It works for precision as well as width.
wid = 10
prec = 3
num = 123.456789
print "%0*.*f" % (wid, prec, num)
gives you -> 000123.457
(It's the same as the printf() function in C.)
-=- Larry -=-
> You might want to try "new style" string formatting [1], which I think
> is better than the "old style" in this particular case:
>
> >>> "Testing {0:0{1}d}".format(42, 4)
> 'Testing 0042'
> >>> "Testing {0:0{1}d}".format(42, 9)
> 'Testing 000000042'
One cannot use a nested field in the 'name' part of the field (before
the ':' (I tried), but are pretty free to nest in the actual
specification part after the ':'.
>>> '{0:{1}}'.format(7,'b')
'111'
>>> '{0:{1}}'.format(7,'d')
'7'
--
Terry Jan Reedy
Thanks all for the many good suggestions - I am looking over them and
reading the referenced docs.
Cheers,
Fred.