如何在数字字符串的左边加上零,使字符串具有特定的长度?


当前回答

另一种方法是使用列表理解和长度检查条件。下面是一个演示:

# input list of strings that we want to prepend zeros
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]

# prepend zeros to make each string to length 8, if length of string is less than 8
In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
Out[83]: ['00101010', '10101010', '00011110', '00000000']

其他回答

str(n).zfill(width)将处理字符串、int、浮点。。。并且兼容Python 2.x和3.x:

>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'

对于保存为整数的邮政编码:

>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

如果你想要相反的:

>>> '99'.ljust(5,'0')
'99000'

我做了一个函数:

def PadNumber(number, n_pad, add_prefix=None):
    number_str = str(number)
    paded_number = number_str.zfill(n_pad)
    if add_prefix:
        paded_number = add_prefix+paded_number
    print(paded_number)

PadNumber(99, 4)
PadNumber(1011, 8, "b'")
PadNumber('7BEF', 6, "#")

输出:

0099
b'00001011
#007BEF

对于使用f-string的Python 3.6+:

>>> i = 1
>>> f"{i:0>2}"  # Works for both numbers and strings.
'01'
>>> f"{i:02}"  # Works only for numbers.
'01'

对于Python 2.6到Python 3.5:

>>> "{:0>2}".format("1")  # Works for both numbers and strings.
'01'
>>> "{:02}".format(1)  # Works only for numbers.
'01'

这些标准格式说明符是[[fill]align][minimumwid]和[0][minimupwid]。