Display number with leading zeros

PythonIntegerString Formatting

Python Problem Overview


How do I display a leading zero for all numbers with less than two digits?

1    →  01
10   →  10
100  →  100

Python Solutions


Solution 1 - Python

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}")

Solution 2 - Python

You can use str.zfill:

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

prints:

01 10 100

Solution 3 - Python

In Python 2.6+ and 3.0+, you would use the format() string method:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

or using the built-in (for a single number):

print(format(i, '02d'))

See the PEP-3101 documentation for the new formatting functions.

Solution 4 - Python

print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

prints:

01 10 100

Solution 5 - Python

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.

Solution 6 - Python

Or this:

print '{0:02d}'.format(1)

Solution 7 - Python

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.

Solution 8 - Python

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

Solution 9 - Python

Or another solution.

"{:0>2}".format(number)

Solution 10 - Python

You can do this with f strings.

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

This will print constant length of 8, and pad the rest with leading 0.

00000001
00000124
00013566

Solution 11 - Python

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
>>>

Solution 12 - Python

Use a format string - http://docs.python.org/lib/typesseq-strings.html

For example:

python -c 'print "%(num)02d" % {"num":5}'

Solution 13 - Python

width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

Solution 14 - Python

Use:

'00'[len(str(i)):] + str(i)

Or with the math module:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)

Solution 15 - Python

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

Solution 16 - Python

This would be the Python way, although I would include the parameter for clarity - "{0:0>2}".format(number), if someone will wants nLeadingZeros they should note they can also do:"{0:0>{1}}".format(number, nLeadingZeros + 1)

Solution 17 - Python

You could also do:

'{:0>2}'.format(1)

which will return a string.

Solution 18 - Python

If dealing with numbers that are either one or two digits:

'0'+str(number)[-2:] or '0{0}'.format(number)[-2:]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionashchristopherView Question on Stackoverflow
Solution 1 - PythonJack M.View Answer on Stackoverflow
Solution 2 - PythonDatageekView Answer on Stackoverflow
Solution 3 - PythonBerView Answer on Stackoverflow
Solution 4 - PythonKresimirView Answer on Stackoverflow
Solution 5 - PythonDimitris Fasarakis HilliardView Answer on Stackoverflow
Solution 6 - PythonajdView Answer on Stackoverflow
Solution 7 - PythonnoskloView Answer on Stackoverflow
Solution 8 - PythonZuLuView Answer on Stackoverflow
Solution 9 - PythonWinterChillyView Answer on Stackoverflow
Solution 10 - PythonNicolas GervaisView Answer on Stackoverflow
Solution 11 - PythonRobertoView Answer on Stackoverflow
Solution 12 - PythonAirsource LtdView Answer on Stackoverflow
Solution 13 - PythonnvdView Answer on Stackoverflow
Solution 14 - PythonLinekioView Answer on Stackoverflow
Solution 15 - PythonhandleView Answer on Stackoverflow
Solution 16 - PythonZahid RiazView Answer on Stackoverflow
Solution 17 - PythonStuart DemmerView Answer on Stackoverflow
Solution 18 - PythonKnowbodyView Answer on Stackoverflow