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


当前回答

只需使用字符串对象的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月起就一直使用这种符号。某物老狗。。一些东西。。。新技巧。

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

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

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

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

要填充字符串:

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

字符串格式文档。

>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

如果你想要相反的:

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