将数字格式化为字符串
如何将数字格式化为字符串,使其前面有多个空格? 我希望较短的数字 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'
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?
a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:' 5/52500'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
格式运算符:
使用
*
规范,字段长度可以是一个参数:Format operator:
Using
*
spec, the field length can be an argument:'%*s/%s' % (len(str(a)), b, a)
'%*s/%s' % (len(str(a)), b, a)
您可以仅使用
%*d
格式化程序来给出宽度。int(math.ceil(math.log(x, 10)))
将为您提供位数。*
修饰符使用一个数字,该数字是一个整数,表示要间隔多少个空格。 因此,通过执行'%*d'
% (width, num)` 您可以指定宽度并渲染数字,而无需任何进一步的 python 字符串操作。这是使用 math.log 来确定“outof”数字的长度的解决方案。
另一个解决方案是将超出的数字转换为字符串并使用 len(),如果您愿意,可以这样做:
You can just use the
%*d
formatter to give a width.int(math.ceil(math.log(x, 10)))
will give you the number of digits. The*
modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing'%*d'
% (width, num)` you can specify the width AND render the number without any further python string manipulation.Here is a solution using math.log to ascertain the length of the 'outof' number.
Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:
请参阅字符串格式化操作:
您仍然需要动态构建您的通过包含最大长度来格式化字符串:
See String Formatting Operations:
You still have to dynamically build your formatting string by including the maximum length:
不确定你到底在追求什么,但这看起来很接近:
如果你想更加动态,请使用类似
rjust
的东西:或者甚至:
Not sure exactly what you're after, but this looks close:
If you want to be more dynamic, use something like
rjust
:Or even: