对齐打印的单独部分

时间:2012-09-14 02:47:09

标签: python python-3.x

我正在尝试将输出中的文字对齐。

purch_amt = float(input('Enter Amount of Purchase'))
state_stax = purch_amt * 0.04
county_stax = purch_amt * 0.02
tax = state_stax + county_stax
totalprice = purch_amt + tax

Print("Purchase Price", "= $", %.2f % purch_amt)
Print("State Sales tax", "= $", %.2f % state_stax)
Print("County Sales tax", "= $", %.2f % county_stax)
Print("Total Tax", "= $", %.2f % tax)
Print("Total Price", "= $", %.2f % totalprice)

...我希望它在运行时看起来像这样。

Purchase Price    = $   100.00
State Sales tax   = $     4.00
County Sales tax  = $     2.00
Total Tax         = $     6.00
Total Price       = $   106.00

我发现这样做的唯一方法是非常复杂的,应该相当容易。

问题解决了,谢谢!

purch_amt = float(input('Enter Amount of Purchase'))
state_stax = purch_amt * 0.04
county_stax = purch_amt * 0.02
tax = state_stax + county_stax
totalprice = purch_amt + tax

def justified(title, amount, titlewidth=20, amountwidth=10):
    return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)

print(justified('Purchase Price', purch_amt))
print(justified('State Sales Tax', state_stax))
print(justified('County Sales Tax', county_stax))
print(justified('Total Tax', tax))
print(justified('Total Price', totalprice))

2 个答案:

答案 0 :(得分:3)

String ljust, rjust, center是你想要填充像这样的字符串。

def justified(title, amount, titlewidth=20, amountwidth=10):
    return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)

print(justified('Parts', 12.45))
print(justified('Labor', 100))
print(justified('Tax', 2.5))
print(justified('Total', 114.95))

答案 1 :(得分:1)

您可以使用内置的string formatting

>>> column_format = "{item:20} = $ {price:>10.2f}"
>>> print(column_format.format(item="Total Tax", price=6))
Total Tax            = $       6.00

...等

打破这个局面:

  • {item}表示格式化名为item
  • 的参数
  • {item:20}表示格式化结果的宽度应为20个字符
  • {price:>10.2f}表示右对齐(>),宽度为10(10),浮点精度为2位小数(.2f

顺便说一句,您可能希望查看Decimal货币工作包。