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
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
prints:
01
10
100
The Pythonic way to do this:
str(number).rjust(string_width, fill_char)
This way, the original string is returned unchanged if its length is greater than string_width. Example:
a = [1, 10, 100]
for num in a:
print str(num).rjust(2, '0')
Results:
01
10
100
x = [1, 10, 100]
for i in x:
print '%02d' % i
results in:
01
10
100
Read more information about string formatting using % in the documentation.
Use a format string - http://docs.python.org/lib/typesseq-strings.html
For example:
python -c 'print "%(num)02d" % {"num":5}'
In Python 2 (and Python 3) you can do:
print "%02d" % (1,)
Basically % is like printf
or sprintf
(see docs).
For Python 3.+, the same behavior can also be achieved with format:
print("{:02d}".format(1))
For Python 3.6+ the same behavior can be achieved with f-strings:
print(f"{1:02d}")
df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))
The 5 is the number of total digits.
I used this link: http://www.datasciencemadesimple.com/add-leading-preceding-zeros-python/