[英]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.