如何在Python中设置可变数字的数字格式?
假设我想在前面显示数字123,其中填充零的数量是可变的。
例如,如果我想用5位数字来显示,那么我会有数字= 5给我:
00123 如果我想用6位数字显示,我会有数字= 6给予:
 000123 
我如何在Python中做到这一点?
有一个名为zfill的string方法:
 >>> '12344'.zfill(10) 0000012344 
它将用零填充string的左侧,使string长度为N(在这种情况下为10)。
 如果您使用format()方法的格式化string,则优先于旧格式的''%格式化 
 >>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123) 'One hundred and twenty three with three leading zeros 000123.' 
 看到 
  http://docs.python.org/library/stdtypes.html#str.format 
  http://docs.python.org/library/string.html#formatstrings 
这是一个宽度可变的例子
 >>> '{num:0{width}}'.format(num=123, width=6) '000123' 
你甚至可以指定填充字符作为variables
 >>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6) '000123' 
 '%0*d' % (5, 123) 
 print "%03d" % (43) 
打印
043
使用string格式
 print '%(#)03d' % {'#': 2} 002 print '%(#)06d' % {'#': 123} 000123 
更多信息: 链接文本
在Python 3.6中引入了格式化的string文字 (简称“f-strings”),现在可以用简单的语法访问以前定义的variables:
 >>> name = "Fred" >>> f"He said his name is {name}." 'He said his name is Fred.' 
John La Rooy给出的例子可以写成
 In [1]: num=123 ...: fill='0' ...: width=6 ...: f'{num:{fill}{width}}' Out[1]: '000123'