numbers = [100, 100.01, 3.1232342341312323434]
for number in numbers:
rounded_number = '{:.8f}'.format(i).rstrip('0').rstrip('.')
centered_number = '{:^14}'.format(rounded_number) # substitute 14 with the desired width
print (centered_number)
# Or, as a one-liner
# print ('{:^14}'.format('{:.8f}'.format(i).rstrip('0').rstrip('.')))
def formatter(value):
return "{:^14.8g}".format(value)
l = [100, 100.01, 3.1232342341312323434,
0.000000000000123, 1234567899.999]
for x in l:
print(formatter(x))
输出:
^{pr2}$
格式化程序函数的一些可能有用的扩展
稍微更改格式化程序函数,以便在调用时设置打印字段的精度和宽度:
def formatter(value, precision, width):
return "{{:^{}.{}g}}".format(width, precision).format(value)
l = [100, 100.01, 3.1232342341312323434,
0.000000000000123, 1234567899.999]
for x in l:
print(formatter(x, 5, 20))
如果
stringwidth
大于生成数字的字符数,则第一个解决方案不起作用,因为它在字符串周围添加空格,rstrip
没有任何效果。在为了让它工作,首先你应该把它弄圆(必要时剥去),然后,作为第二步-居中。因此,我们有:
输出:
^{pr2}$回答您的问题:
只需使用float表示类型},如Format Specification Mini-Language所述。这将自动丢弃尾随的零。另外,如果需要的话,它会转换成指数表示法。在
'{:g}'
,而不是{输出:
^{pr2}$格式化程序函数的一些可能有用的扩展
稍微更改格式化程序函数,以便在调用时设置打印字段的精度和宽度:
输出:
我在这个页面上找到了关于Pandas Formatting Snippets的嵌套format()函数
你可以这样做:
其中stringwidth是所需输出的宽度,其中值应居中。在
相关问题 更多 >
编程相关推荐