+1 vote
in Programming Languages by (14.7k points)
How can I pad a numeric value on the left with zeros? I want to do this for the alignment of values in a column.

E.g.

12 -> 00012

1 Answer

0 votes
by (25.6k points)

You need to convert the numeric value to string and then you apply the method zfill() on the string to pad it with zeros on the left.

E.g.

>>> str(12).zfill(5)
'00012'

If you want to right-justify a string, you can use the method rjust() to pad it with spaces on the left. 

E.g.

>>> str(12).rjust(5)
'   12'

...