我需要将前导零添加到整数,使一个具有定义数量的数字($cnt)的字符串。 把这个简单的函数从PHP翻译成Python的最好方法是什么:

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

有没有函数可以做到这一点?


当前回答

对于Python 3及以上版本: Str.zfill()仍然是最易读的选项

但是研究一下新的强大的str.format()是一个好主意,如果你想填充一些不为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

其他回答

你很可能只需要格式化你的整数:

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

例如,

>>> '%0*d' % (3, 4)
'004'

内置zfill的一行程序替代。

此函数接受x并将其转换为字符串,仅在长度太短时才在开头添加0:

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

总而言之,内置:zfill已经足够好了,但是如果有人想知道如何手动实现它,这里还有一个例子。

你可以使用zfill()方法填充一个零字符串:

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

你至少有两个选择:

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

如果在Python >2.5上,请参阅clorz回答中的第三个选项。

这是我的Python函数:

def add_nulls(num, cnt=2):
  cnt = cnt - len(str(num))
  nulls = '0' * cnt
  return '%s%s' % (nulls, num)