Display number with leading zeros

integer, python, string-formatting

Solution

In Python 2 (and Python 3) you can do:

number = 1
print("%02d" % (number,))

Basically % is like `printf` or `sprintf` (see docs).

For Python 3.+, the same behavior can also be achieved with `format`:

number = 1
print("{:02d}".format(number))

For Python 3.6+ the same behavior can be achieved with f-strings:

number = 1
print(f"{number:02d}")

Problem

How do I display a leading zero for all numbers with less than two digits? ``` 1 → 01 10 → 10 100 → 100 ```

Original source

Related problems