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


当前回答

要填充字符串:

>>> n = '4'
>>> print(n.zfill(3))
004

要填充数字:

>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
004

字符串格式文档。

其他回答

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

# 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']

您也可以重复“0”,将其前置到str(n)并获得最右侧的宽度切片。又快又脏的小表情。

def pad_left(n, width, pad="0"):
    return ((pad * width) + str(n))[-width:]

我做了一个函数:

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中字符串长度的int,因为它似乎没有被覆盖:

>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'

对于使用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]。