Best way to format integer as string with leading zeros?


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?

4/9/2009 11:58:55 AM

Accepted Answer

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

In [3]: str(1).zfill(2)
Out[3]: '01'
4/9/2009 9:23:23 AM

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.

i = random.randint(0,99999)
print "%05d" % i

which will output an string of length 5.

Edit: In Python2.6 and above, there is also:

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow