1373

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

1    →  01
10   →  10
100  →  100
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
ashchristopher
  • 25,143
  • 18
  • 48
  • 49

19 Answers19

1811

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}")
Flimm
  • 136,138
  • 45
  • 251
  • 267
Jack M.
  • 30,350
  • 7
  • 55
  • 67
  • 12
    Example: print "%05d" % result['postalCode'] for a 5 digit postal code. – Nick Woodhams Jun 05 '12 at 12:08
  • 5
    `x = "%02d.txt" % i` raises TypeError (cannot concatenate 'str' and 'int' objects), but `x = "%02d.txt" % (i,)` does not. Interesting. I wonder where is that documented – theta Nov 05 '12 at 18:10
  • 2
    @theta In 2.7.6, I don't get an error. Maybe this was a bug in a specific version of Python that they've since fixed? – Jack M. Apr 04 '14 at 14:51
  • 3
    Maybe. In 2.7.6 there is no exception if format value isn't tuple (at least for this example). Looking at the date of my comment I guess I was running 2.7.3 back then, and at that time I didn't know that putting single variable in a tuple gets you on a safe side while using `%` string formater. – theta Apr 04 '14 at 15:41
  • 6
    To elaborate, the [docs](https://docs.python.org/2/library/string.html#format-specification-mini-language) explain this here: "When no explicit alignment is given, preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '='." – JHS Mar 30 '16 at 19:48
  • 1
    What if I want the `2` in `:02` to be a variable? – Apollys supports Monica Sep 24 '19 at 22:52
  • @Apollys This may be better suited to Datageek's answer below. https://stackoverflow.com/a/3371180/3421 – Jack M. Oct 17 '19 at 15:57
  • The second example also works in [python2.7](https://docs.python.org/2.7/library/string.html#formatstrings) – kayochin Aug 03 '21 at 08:24
  • Is it possible to achieve that for float numbers? I mean what should the formatting string look like for `foo = 3.95` to print `foo`'s value as `003.950`? I know how to set precision for fractional part, but what about integer part? – Евгений Крамаров Oct 10 '21 at 19:47
1209

You can use str.zfill:

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

prints:

01
10
100
Neuron
  • 5,141
  • 5
  • 38
  • 59
Datageek
  • 25,977
  • 6
  • 66
  • 70
  • 90
    I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable... e.g. x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb. – EroSan Feb 24 '11 at 17:33
  • 6
    This should be the correct answer, since the `"{1:02d}"` cannot have variables in place of `2` (like if you are creating a dynamic function). – Joshua Varghese May 20 '20 at 10:37
  • 5
    @JoshuaVarghese It can have variables: `"{0:0{1}}"`. Pass any number of zeros you want as the second argument. – Jim Aug 19 '20 at 22:46
  • This method also works well for prepending zeroes to floating point numbers. – kfmfe04 Mar 11 '22 at 20:44
385

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.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Ber
  • 40,356
  • 16
  • 72
  • 88
  • 30
    Works in Python 2.7.5 as well. You can also use '{:02d}'.format(1) if you don't want to use named arguments. – Jason Martens Jan 07 '14 at 14:20
  • 1
    Works fine in 2.7.2, with a floating point "{0:04.0f}".format(1.1) gives 0001 (:04 = at least 4 characters, in this case leading 0's, .0f = floating point with no decimals). I am aware of the % formatting but wanted to modify an existing .format statement without rewriting the *whole* thing. Thanks! – Michael Stimson Jul 21 '15 at 01:31
158
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

prints:

01
10
100
Neuron
  • 5,141
  • 5
  • 38
  • 59
Kresimir
  • 2,930
  • 1
  • 19
  • 13
  • 1
    This way let you repeat the argument several times within the string: `One zero:{0:02}, two zeros: {0:03}, ninezeros: {0:010}'.format(6)` – srodriguex Apr 14 '14 at 21:00
  • 2
    Only compatible with Python 3. If using Python 2.7, do `print '{:02}'.format(1)` – Blairg23 Jan 31 '17 at 23:30
114

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
93

Or this:

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

ajd
  • 947
  • 6
  • 2
73
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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • 9
    The documentation example sucks. They throw mapping in with the leading zero sample, so it's hard to know which is which unless you already know how it works. Thats what brought me here, actually. – Grant Jul 01 '09 at 17:52
60

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
Neuron
  • 5,141
  • 5
  • 38
  • 59
ZuLu
  • 933
  • 8
  • 17
35

Or another solution.

"{:0>2}".format(number)
Kenly
  • 24,317
  • 7
  • 44
  • 60
WinterChilly
  • 1,549
  • 3
  • 21
  • 34
  • 4
    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)` – Jonathan Allan Apr 24 '16 at 18:33
9

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
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
8

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
>>> 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roberto
  • 446
  • 5
  • 11
6

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

For example:

python -c 'print "%(num)02d" % {"num":5}'
Airsource Ltd
  • 32,379
  • 13
  • 71
  • 75
6

Its built into python with string formatting

f'{number:02d}'
thosbrown
  • 79
  • 1
  • 2
  • This old question doesn't need any more answers. Your answer is also a duplicate of the accepted answer without any additional information. – thedemons Nov 13 '22 at 19:05
4
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
nvd
  • 2,995
  • 28
  • 16
4

You could also do:

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

which will return a string.

Stuart Demmer
  • 196
  • 1
  • 5
2

Use:

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

Or with the math module:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Linekio
  • 21
  • 2
2

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
handle
  • 5,859
  • 3
  • 54
  • 82
1

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)

Zahid Riaz
  • 11
  • 2
-2

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

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

Knowbody
  • 66
  • 5