left padding zeroes on a string...
George Sakkis
gsakkis at rutgers.edu
Fri Mar 25 17:35:35 EST 2005
"cjl" <cjlesh at gmail.com> wrote:
> Hey all:
>
> 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.
Actually in this case string2 is padded with spaces, instead of zeros.
>If I cast string1 as an int it works:
>
> string1 = '32'
> int2 = "%03d" % (int(string1))
> print int2
>
> >032
>
> Of course, I need to cast the result back to a string to use it. Why
> doesn't the first example work?
That's not correct; int2 is a string so you can use it directly (and probably rename it to something
more appropriate).
> -cjl
Regards,
George
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To see victory only when it is within the ken of the common herd is not
the acme of excellence."
Sun Tzu, 'The Art of War'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the Python-list
mailing list