Given:
a = 1 b = 10 c = 100
How do I display a leading zero for all numbers with less than two digits?
This is the output I'm expecting:
01 10 100
Use the "0"# format when you want to display one leading zero. When you use this format, the numbers that you type and the numbers that Microsoft Excel displays are listed in the following table. Example 2: Use the "000"# format when you want to display three leading zeros.
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
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}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With