[英]How do I format a number with a variable number of digits in Python?
Say I wanted to display the number 123 with a variable number of padded zeroes on the front.假设我想显示数字 123,并在前面显示可变数量的填充零。
For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:例如,如果我想以 5 位数字显示它,我会让数字 = 5 给我:
00123
If I wanted to display it in 6 digits I would have digits = 6 giving:如果我想以 6 位数字显示它,我将有数字 = 6 给出:
000123
How would I do this in Python?我将如何在 Python 中做到这一点?
If you are using it in a formatted string with the format()
method which is preferred over the older style ''%
formatting如果您在格式化字符串中使用
format()
方法,该方法优于旧样式''%
格式
>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
See看
http://docs.python.org/library/stdtypes.html#str.format http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings http://docs.python.org/library/string.html#formatstrings
Here is an example with variable width这是一个具有可变宽度的示例
>>> '{num:0{width}}'.format(num=123, width=6)
'000123'
You can even specify the fill char as a variable您甚至可以将填充字符指定为变量
>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
There is a string method called zfill:有一个名为 zfill 的字符串方法:
>>> '12344'.zfill(10)
0000012344
It will pad the left side of the string with zeros to make the string length N (10 in this case).它将用零填充字符串的左侧,使字符串长度为 N(在本例中为 10)。
'%0*d' % (5, 123)
With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to access previously defined variables with a briefer syntax:随着 Python 3.6 中格式化字符串文字(简称“f-strings”) 的引入,现在可以使用更简洁的语法访问以前定义的变量:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
The examples given by John La Rooy can be written as John La Rooy 给出的例子可以写成
In [1]: num=123
...: fill='0'
...: width=6
...: f'{num:{fill}{width}}'
Out[1]: '000123'
print "%03d" % (43)
Prints印刷
043
043
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.