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


当前回答

对于那些来这里理解而不仅仅是快速回答的人来说。我特别针对时间字符串:

hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03

"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'

"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'

"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'

“0”符号替换为“2”填充字符,默认值为空白“>”符号表示字符串左侧的所有2“0”字符“:”符号format_spec

其他回答

要填充字符串:

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

只需使用字符串对象的rjust方法。

此示例创建一个10个字符长度的字符串,根据需要进行填充:

>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'

我做了一个函数:

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
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

如果你想要相反的:

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