使用.format()方法在Python 3.3中格式化文本

SIS*_*SYN 12 python python-3.x

我是Python的新手,并试图处理一些示例脚本.我正在做一个简单的现金注册类型的事情,但我想证明或正确对齐输出,使它看起来像这样:

subTotal = 24.95
tax = subTotal * 0.0725
total = subTotal + tax
paid = 30
change = paid-total
print("The subtotal was: $",subTotal)
print("The tax was: $",tax)
print("The total was: $",total)
print("The customer paid: $",paid)
print("Change due: $",change)
Run Code Online (Sandbox Code Playgroud)

我知道我可以用更少的打印语句简化这一点,但我只是希望它更容易看到我正在尝试做什么.

我希望它输出这样的东西,注意美元金额全部对齐,并且$和美元金额之间没有空格.我不知道怎么做这两件事.

The subtotal was:   $24.95
The tax was:         $1.81
The total was:      $26.76
The customer paid:  $30.00
Change due:          $3.24
Run Code Online (Sandbox Code Playgroud)

我尝试阅读格式方法的Python文档,但我没有看到任何格式说明符可用于执行某些操作的示例.在此先感谢您的帮助.

Cha*_*net 10

金额可以这样形成:

"${:.2f}".format(amount)
Run Code Online (Sandbox Code Playgroud)

您可以为字符串添加填充,例如宽度为20:

"{:20s}".format(mystring)
Run Code Online (Sandbox Code Playgroud)

您可以右对齐字符串,例如宽度为7:

"{:>7s}".format(mystring)
Run Code Online (Sandbox Code Playgroud)

将所有这些放在一起:

s = "The subtotal was:"
a = 24.95
print("{:20s}{:>7s}".format(s, "${.2f}".format(a))
Run Code Online (Sandbox Code Playgroud)