-2

Is there a format function in python that turn for example 4 to 04 but 10 not in 010.

The idea is that all numbers under 10 are represented by 0and then the number.

Already thanks a lot.

Jirka
  • 391
  • 1
  • 2
  • 14

2 Answers2

0

The regular formatting with % supports leading zeros with %0xd where x is the total number of digits:

>>> print("%02d" % 4)
04
>>> print("%02d" % 10)
10
Pavel
  • 7,436
  • 2
  • 29
  • 42
0

You would have to use a string as Python does not allow you to have integers with leading 0s. As if we define one, we get an error:

>>> a = 09
  File "<stdin>", line 1
    a = 09
         ^
SyntaxError: invalid token

So the way we can achieve this is to first convert to a string and then use .zfill:

def pad(n, l):
    return str(n).zfill(l)

and some tests:

>>> pad(4, 2)
'04'
>>> pad(10, 2)
'10'
>>> pad(67, 20)
'00000000000000000067'

On the other hand, if you only want to pad one-digit integers to two-digit string, then you could use a ternary expression:

def pad2(n):
    s = str(n)
    return "0" + s if len(s) < 2 else s

and some tests again:

>>> pad2(4)
'04'
>>> pad2(10)
'10'
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54