Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python 3.6使用小数点对数字进行右对齐_Python - Fatal编程技术网

如何使用Python 3.6使用小数点对数字进行右对齐

如何使用Python 3.6使用小数点对数字进行右对齐,python,Python,我正在寻找一种方法,使用Python 3.6.1对输出中的数字进行右对齐,以便所有小数点对齐 我使用的一般格式是: print('Bonus: $',format(bonus, ',.2f'),sep='') 但我不知道如何让这些数字正确地解释并保持货币格式。以下是输出的图片: 链接字符串格式化程序的工作原理: >>> "Cash Money: %10s" % "$%.2f" % 6.124 'Cash Money: $6.12' 第一个添加符号并格式化数字,第

我正在寻找一种方法,使用Python 3.6.1对输出中的数字进行右对齐,以便所有小数点对齐

我使用的一般格式是:

print('Bonus: $',format(bonus, ',.2f'),sep='') 
但我不知道如何让这些数字正确地解释并保持货币格式。以下是输出的图片:


链接字符串格式化程序的工作原理:

>>> "Cash Money: %10s" % "$%.2f" % 6.124
'Cash Money:      $6.12'
第一个添加符号并格式化数字,第二个将其填充到适当的长度

以更现实的方式使用:

str_bal = "$%.2f" % bal
print "Balance: %20s" % str_bal
一个真实的例子:

我构建了一个报告,它通过混合格式字符串智能地调整大小:

format_string = "%-9s %-{}s %6.3f%% (%{}i/%{}i) total events: %{}i".format(
                 max_len_key, max_len_pos, max_len_total, max_len_events)
for entry in table:
    ...
    print format_string % (title, key, percent, pos, total, event)
哪些产出:

Version:  1.0.0.0  2.688% (10/372) total events: 150
Version:  1.4.1.15 0.000% ( 0/181) total events:  73
注意:您可以在不混合格式化程序的情况下执行此操作,但我认为这比令人讨厌的
“%%-9s%%-%is%%6.3f%%%(%%ii/%%ii)总事件数:%%%ii”
(这是第一个格式字符串的有效替换)。

您可以使用:

print('{:<15}: {:>10.2f}'.format('Bonus', bonus),sep='') 
print({:10.2f})。格式('Bonus',Bonus),sep='')

>负责右对齐,而.2f负责小数点

你对数字有什么限制吗?最简单的方法将强制您确定该值可以包含的最大位数。例如,
str.rjust()