'How do I zero-pad a number? [duplicate]

I'm trying to make a number guesser that starts from 000001 and counts up all the way to 999999 how can I do that?



Solution 1:[1]

You can use str.format() like this:

num = 2
print("num: {0:03d}".format(num))

output:

num: 002

Solution 2:[2]

For dynamically choosing the pad-width:

>>> num_digits = 6
>>> f"{str(x).rjust(num_digits, '0')}"
'000003'
>>> num_digits = 3
>>> f"{str(x).rjust(num_digits, '0')}"
'003'
>>> x = 521
>>> f"{str(x).rjust(num_digits, '0')}"
'521'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hata
Solution 2 ddejohn