# beautiful and fast (if you know in advance how many to pad) >>> "%03d" % 2 '002' >>> "%04d" % 22 '0022'for more information read the format-specification-mini-language. Thanks Sanne!
an alternative offered by nfloyd is
# if you only know at runtime how much to pad >>> i = 4 >>> str(i).zfill(3) '004'or
>>> '{:07d}'.format(20) '0000020'