[英]Format a number as a string
如何將數字格式化為字符串,使其前面有多個空格? 我希望較短的數字 5 在其前面有足夠的空格,以便空格加上 5 的長度與 52500 相同。下面的過程有效,但是有內置的方法嗎?
a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:' 5/52500'
您可以只使用%*d
格式化程序來提供寬度。 int(math.ceil(math.log(x, 10)))
會給你位數。 *
修飾符使用一個數字,該數字是 integer,表示要間隔多少個空格。 因此,通過執行'%*d'
% (width, num)`,您可以指定寬度並呈現數字,而無需任何進一步的 python 字符串操作。
這是使用 math.log 確定“outof”數字長度的解決方案。
import math
num = 5
outof = 52500
formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)
另一種解決方案涉及將 outof 數字轉換為字符串並使用 len(),如果您願意,可以這樣做:
num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)
'%*s/%s' % (len(str(a)), b, a)
請參閱 字符串格式化操作:
s = '%5i' % (5,)
您仍然必須通過包含最大長度來動態構建格式化字符串:
fmt = '%%%ii' % (len('52500'),)
s = fmt % (5,)
不確定您到底在追求什么,但這看起來很接近:
>>> n = 50
>>> print "%5d" % n
50
如果您想更有活力,請使用rjust
之類的東西:
>>> big_number = 52500
>>> n = 50
>>> print ("%d" % n).rjust(len(str(52500)))
50
甚至:
>>> n = 50
>>> width = str(len(str(52500)))
>>> ('%' + width + 'd') % n
' 50'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.