
填充数字字符串到左边的最有趣的方法是什么,即数字字符串有特定的长度?
的字符串:
>>> n = '4'
>>> print n.zfill(3)
004
和数字:
>>> n = 4
>>> print '%03d' % n
004
>>> print format(n, '03') # python >= 2.6
004
>>> print '{0:03d}'.format(n) # python >= 2.6
004
>>> print '{foo:03d}'.format(foo=n) # python >= 2.6
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
>>> print('{0:03d}'.format(n)) # python 3
004
>>> print(f'{n:03}') # python >= 3.6
004
只要使用字符串对象的 rjust 方法即可。
这个例子会产生一个10个字符的字符串,必要时填充。
>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
未经作者同意,本文严禁转载,违者必究!




近期评论