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 expe
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
Use:
'00'[len(str(i)):] + str(i)
Or with the math
module:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
This is how I do it:
str(1).zfill(len(str(total)))
Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:
Python 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> total = 100 >>> print(str(1).zfill(len(str(total)))) 001 >>> total = 1000 >>> print(str(1).zfill(len(str(total)))) 0001 >>> total = 10000 >>> print(str(1).zfill(len(str(total)))) 00001 >>>
You can use str.zfill:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
Or this:
print '{0:02d}'.format(1)
Or another solution.
"{:0>2}".format(number)