简体   繁体   English

将数字格式化为字符串

[英]Format a number as a string

How do you format a number as a string so that it takes a number of spaces in front of it?如何将数字格式化为字符串,使其前面有多个空格? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?我希望较短的数字 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'

Format operator :格式运算符

>>> "%10d" % 5
'         5'
>>> 

Using * spec, the field length can be an argument:使用* spec,字段长度可以是一个参数:

>>> "%*d" % (10,5)
'         5'
>>> 

You can just use the %*d formatter to give a width.您可以只使用%*d格式化程序来提供宽度。 int(math.ceil(math.log(x, 10))) will give you the number of digits. int(math.ceil(math.log(x, 10)))会给你位数。 The * modifier consumes a number, that number is an integer that means how many spaces to space by. *修饰符使用一个数字,该数字是 integer,表示要间隔多少个空格。 So by doing '%*d' % (width, num)` you can specify the width AND render the number without any further python string manipulation.因此,通过执行'%*d' % (width, num)`,您可以指定宽度并呈现数字,而无需任何进一步的 python 字符串操作。

Here is a solution using math.log to ascertain the length of the 'outof' number.这是使用 math.log 确定“outof”数字长度的解决方案。

import math
num = 5
outof = 52500
formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)

Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:另一种解决方案涉及将 outof 数字转换为字符串并使用 len(),如果您愿意,可以这样做:

num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)

'%*s/%s' % (len(str(a)), b, a) '%*s/%s' % (len(str(a)), b, a)

See String Formatting Operations :请参阅 字符串格式化操作

s = '%5i' % (5,)

You still have to dynamically build your formatting string by including the maximum length:您仍然必须通过包含最大长度来动态构建格式化字符串:

fmt = '%%%ii' % (len('52500'),)
s = fmt % (5,)

Not sure exactly what you're after, but this looks close:不确定您到底在追求什么,但这看起来很接近:

>>> n = 50
>>> print "%5d" % n
   50

If you want to be more dynamic, use something like rjust :如果您想更有活力,请使用rjust之类的东西:

>>> big_number = 52500
>>> n = 50
>>> print ("%d" % n).rjust(len(str(52500)))
   50

Or even:甚至:

>>> n = 50
>>> width = str(len(str(52500)))
>>> ('%' + width + 'd') % n
'   50'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM