Dynamic Zero Padding.

  • Thread starter Friedrich Clausen
  • Start date
F

Friedrich Clausen

Hello All,

I want to print some integers in a zero padded fashion, eg. :
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.
 
M

Mel

Friedrich said:
I want to print some integers in a zero padded fashion, eg. :

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.

:)

('%%0%dd' % (pads,)) % (n,)

Probably be good to wrap it in a function. It looks kind of obscure as it
is.

Mel.
 
H

harrismh777

Friedrich said:
I would be much obliged if someone can give me some tips on how to
achieve a variably pad a number.

testing 0001




kind regards,
m harris
 
C

Chris Angelico

:)

('%%0%dd' % (pads,)) % (n,)

Probably be good to wrap it in a function.  It looks kind of obscure asit
is.

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
 
T

Terry Reedy

You might want to try "new style" string formatting [1], which I think
is better than the "old style" in this particular case:
'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 ':'.
'7'
 
F

Friedrich Clausen

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 ':'.
'7'

Thanks all for the many good suggestions - I am looking over them and
reading the referenced docs.

Cheers,

Fred.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top