left padding zeroes on a string...

John Machin sjmachin at lexicon.net
Fri Mar 25 17:41:40 EST 2005


cjl wrote:
> I want to convert strings (ex. '3', '32') to strings with left padded
> zeroes (ex. '003', '032'), so I tried this:
>
> string1 = '32'
> string2 = "%03s" % (string1)
> print string2
>
> >32
>
> This doesn't work.

Documentation == """
Flag Meaning
0 The conversion will be zero padded for numeric values.
"""

"Numeric values" means when converting from a numeric value as in
"%03d", but not "%03s". If you think "numeric values" is vague or
misleading -- K&R (v2 p243) has "numeric conversions" -- then submit a
documentation patch.

> If I cast string1 as an int it works:

Python doesn't have casts. You mean "convert".

You may like to consider the zfill method of string objects:

>>> "3".zfill(5)
'00003'

or the even more versatile rjust method:

>>> "3".rjust(5, '0')
'00003'
>>> "3".rjust(5, '*')
'****3'
>>>

HTH,
John




More information about the Python-list mailing list