+1 vote
in Programming Languages by (73.8k 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

+1 vote
by (348k points)
selected by
 
Best answer

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'


...