簡體   English   中英

如何在 Python 中格式化具有可變位數的數字?

[英]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”) 的引入,現在可以使用更簡潔的語法訪問以前定義的變量:

>>> 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'

對於那些想用 python 3.6+ 和f-Strings做同樣事情的人來說,這是解決方案。

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
print "%03d" % (43)

印刷

043

使用字符串格式

print '%(#)03d' % {'#': 2}
002
print '%(#)06d' % {'#': 123}
000123

更多信息在這里: 鏈接文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM