如何在字符串前添加零?

2173 投票
19 回答
1542997 浏览
提问于 2025-04-11 19:41

我想知道怎么在一个数字字符串的左边加上零,这样这个字符串就能达到我想要的长度。

19 个回答

217

除了 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-字符串 的详细说明可以查看文档。

489

只需要使用字符串对象的 rjust 方法就可以了。

这个例子创建了一个长度为10个字符的字符串,并根据需要添加空格:

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

要给字符串添加填充:

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

字符串格式化的相关文档

撰写回答