如何将数字格式化为字符串,使其前面有多个空格?我希望较短的数字 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)))
会给你位数。修饰符使用*
一个数字,该数字是一个整数,表示要间隔多少个空格。因此,通过执行'%*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'