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


当前回答

除了zfill,您还可以使用常规字符串格式:

print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))

字符串格式和f-string的文档。

其他回答

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

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

>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005

有关所有令人兴奋的详细信息,请参阅打印文档!

Python 3.x更新(7.5年后)

最后一行现在应该是:

print("%0*d" % (width, x))

即print()现在是一个函数,而不是一个语句。注意,我仍然更喜欢Old School printf()风格,因为IMNSHO,它读起来更好,而且,嗯,我从1980年1月起就一直使用这种符号。某物老狗。。一些东西。。。新技巧。

要填充字符串:

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

字符串格式文档。

也可以:

 h = 2
 m = 7
 s = 3
 print("%02d:%02d:%02d" % (h, m, s))

因此输出将为:“02:07:03”

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'