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
You can use str.zfill
:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:
f'{val:02}'
which prints the variable with name val
with a fill
value of 0
and a width
of 2
.
For your specific example you can do this nicely in a loop:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
which prints:
01
10
100
For more information on f-strings, take a look at PEP 498 where they were introduced.
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.
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 >>>
Use a format string - http://docs.python.org/lib/typesseq-strings.html
For example:
python -c 'print "%(num)02d" % {"num":5}'
All of these create the string "01":
>python -m timeit "'{:02d}'.format(1)"
1000000 loops, best of 5: 357 nsec per loop
>python -m timeit "'{0:0{1}d}'.format(1,2)"
500000 loops, best of 5: 607 nsec per loop
>python -m timeit "f'{1:02d}'"
1000000 loops, best of 5: 281 nsec per loop
>python -m timeit "f'{1:0{2}d}'"
500000 loops, best of 5: 423 nsec per loop
>python -m timeit "str(1).zfill(2)"
1000000 loops, best of 5: 271 nsec per loop
>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
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/