[英]Python - How do I format a hexadecimal number in uppercase and two digits?
[英]How do I format a number with a variable number of digits in Python?
假设我想显示数字 123,并在前面显示可变数量的填充零。
例如,如果我想以 5 位数字显示它,我会让数字 = 5 给我:
00123
如果我想以 6 位数字显示它,我将有数字 = 6 给出:
000123
我将如何在 Python 中做到这一点?
如果您在格式化字符串中使用format()
方法,该方法优于旧样式''%
格式
>>> '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'
您甚至可以将填充字符指定为变量
>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
有一个名为 zfill 的字符串方法:
>>> '12344'.zfill(10)
0000012344
它将用零填充字符串的左侧,使字符串长度为 N(在本例中为 10)。
'%0*d' % (5, 123)
对于那些想用 python 3.6+ 和f-Strings做同样事情的人来说,这是解决方案。
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
print "%03d" % (43)
印刷
043
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.