views:

4122

answers:

7

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?

+17  A: 

you most likely just need to format your integer:

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

e.g.

>>> '%0*d' % (3, 4)
'004'
SilentGhost
The question is - how to add not permanent quantity of zeros
ramusus
+1 formatting is the way to go
David Zaslavsky
no that's not a question.
SilentGhost
This is not permanent - in fact you cannot add zeroes permanently to the from of an int - that would then be interpreted as an octal value.
Matthew Schinckel
@Matthew Schnickel: I think the OP wants to know a method to compute the number of zeros he needs. Formatting handles that fine. And int(x, 10) handles the leading zeros.
unbeknown
+15  A: 

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

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

This is my python function:

def add_nulls(num, cnt=2):
  cnt = cnt - len(str(num))
  nulls = '0' * cnt
  return '%s%s' % (nulls, num)
Emre
Which is what str.zfill does :)
ΤΖΩΤΖΙΟΥ
yes :) another method is this:'%03d' % 8
Emre
A: 

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
rpr
+1  A: 

Python 2.6 allows this:

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

>>>add_nulls(2,3)
'002'
clorz
+3  A: 

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.

ΤΖΩΤΖΙΟΥ
A: 

Just for the culture, on PHP, you have the function str_pad which makes exactly the job of your function add_nulls.

str_pad($int, $cnt, '0', STR_PAD_LEFT);
Rémy BOURGOIN