Best way to format integer as string with leading zeros?

Question:

I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt).
What the best way to translate this simple function from PHP to Python:

function add_nulls($int, $cnt=2) {
    $int = intval($int);
    for($i=0; $i<($cnt-strlen($int)); $i++)
        $nulls .= '0';
    return $nulls.$int;
}

Is there a function that can do this?

Asked By: ramusus

||

Answers:

You most likely just need to format your integer:

'%0*d' % (fill, your_int)

For example,

>>> '%0*d' % (3, 4)
'004'
Answered By: SilentGhost

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'
Answered By: unbeknown

This is my Python function:

def add_nulls(num, cnt=2):
  cnt = cnt - len(str(num))
  nulls = '0' * cnt
  return '%s%s' % (nulls, num)
Answered By: Emre Köse

A straightforward conversion would be (again with a function):

def add_nulls2(int, cnt):
    nulls = str(int)
    for i in range(cnt - len(str(int))):
        nulls = '0' + nulls
    return nulls
Answered By: rpr

Python 2.6 allows this:

add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)

>>>add_nulls(2,3)
'002'
Answered By: clorz

You have at least two options:

  • str.zfill: lambda n, cnt=2: str(n).zfill(cnt)
  • % formatting: lambda n, cnt=2: "%0*d" % (cnt, n)

If on Python >2.5, see a third option in clorz’s answer.

Answered By: tzot

One-liner alternative to the built-in zfill.

This function takes x and converts it to a string, and adds zeros in the beginning only and only if the length is too short:

def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )

To sum it up – build-in: zfill is good enough, but if someone is curious on how to implement this by hand, here is one more example.

The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.

To output a string of length 5:


… in Python 3.5 and above: f-strings.

i = random.randint(0, 99999)
print(f'{i:05d}')

Search for f-strings here for more details.


… Python 2.6 and above:

print '{0:05d}'.format(i)

… before Python 2.6:

print "%05d" % i

See: https://docs.python.org/3/library/string.html

Answered By: user518450

For Python 3 and beyond:
str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022
Answered By: YunliuStorage

Python 3.6 f-strings allows us to add leading zeros easily:

number = 5
print(f' now we have leading zeros in {number:02d}')

Have a look at this good post about this feature.

Answered By: SergioAraujo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.