Edd*_*ddy 57 python string string-formatting number-formatting
假设我想在前面显示带有可变数量的填充零的数字123.
例如,如果我想以5位数显示它,我会有数字= 5给我:
00123
Run Code Online (Sandbox Code Playgroud)
如果我想以6位数显示它,我会有数字= 6给出:
000123
Run Code Online (Sandbox Code Playgroud)
我将如何在Python中执行此操作?
Joh*_*ooy 161
如果您在格式化的字符串中使用它,其format()方法比旧样式''%格式更受欢迎
>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
Run Code Online (Sandbox Code Playgroud)
请参阅
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'
Run Code Online (Sandbox Code Playgroud)
您甚至可以将fill char指定为变量
>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
Run Code Online (Sandbox Code Playgroud)
Don*_*ner 36
有一个名为zfill的字符串方法:
>>> '12344'.zfill(10)
0000012344
Run Code Online (Sandbox Code Playgroud)
它将用零填充字符串的左侧以使字符串长度为N(在这种情况下为10).
Ign*_*ams 18
'%0*d' % (5, 123)
Run Code Online (Sandbox Code Playgroud)
Pra*_*rni 11
对于那些想用 python 3.6+ 和f-Strings做同样事情的人来说,这是解决方案。
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
Run Code Online (Sandbox Code Playgroud)
随着Python 3.6 中格式化字符串文字(简称为“ f-strings”)的引入,现在可以使用更简短的语法访问先前定义的变量:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
Run Code Online (Sandbox Code Playgroud)
John La Rooy给出的示例可以写成
In [1]: num=123
...: fill='0'
...: width=6
...: f'{num:{fill}{width}}'
Out[1]: '000123'
Run Code Online (Sandbox Code Playgroud)