如何将$符号放在string.format()的固定宽度字段中

时间:2018-08-08 02:37:07

标签: python

我有以下代码行

print("Income $ {:>8,d} pays Flat tax ${:>9.2f} and Current tax ${:>9.2f}".format(income,tax,curr_tax))

它给了我输出

Income $   10,000 pays Flat tax $     0.00 and Current tax $     0.00

但是我试图将$符号与数字连接起来,中间没有空格。我们如何使用string.format()

编辑:

这是我想要实现的输出

Income    $50,000 pays Flat tax    $780.00 and Current tax      $0.00
Income     $10,00 pays Flat tax      $0.00 and Current tax      $0.00

2 个答案:

答案 0 :(得分:1)

您可以在formatformat

print("Income {:>8} pays Flat tax {:>9} and Current tax {:>9}".format('${:,d}'.format(income), '${:.2f}'.format(tax), '${:.2f}'.format(curr_tax)))

哪个给

Income  $10,000 pays Flat tax     $0.00 and Current tax     $0.00
Income  $50,000 pays Flat tax   $780.00 and Current tax     $0.00

答案 1 :(得分:0)

@aydow有一个肯定的答案。

或者,通过将>更改为<,使用@student注释:

print("Income ${:<8,d} pays Flat tax ${:<9.2f} and Current tax ${:<9.2f}".format(10000,0.00,0.00))

结果:

Income $10,000   pays Flat tax $0.00      and Current tax $0.00

仍然在值之后留空白,但不确定是否会打扰您。