Nicest way to pad zeroes to string
什么是填充数字字符串最左边的零的最pythonic方式,即,所以数字字符串具有特定的长度?
Strings:
>>> n = '4'
>>> print n.zfill(3)
004
And for numbers:
>>> 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
String formatting documentation.
Just use the rjust method of the string object.
This example will make a string of 10 characters long, padding as necessary.
>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
For numbers:
print "%05d" % number
See also: Python: String formatting.
EDIT : It's worth noting that as of yesterday December 3rd, 2008, this method of formatting is deprecated in favour of the format
string method:
print("{0:05d}".format(number)) # or
print(format(number, "05d"))
See PEP 3101 for details.
链接地址: http://www.djcxy.com/p/54298.html下一篇: 最好的方式填充零字符串