2012-09-14 81 views
1

我正在嘗試對齊輸出中的文本。對齊打印的單獨部分

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)) 
+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)) 
+0

我想指出一些[最新的文檔](http://docs.python.org/library/string.html#string.ljust)。另外,'print'foo''需要替換爲Python 3的print('foo')'。 – Blender

+0

好的,謝謝。 – Omnikrys

+0

正是我在找的! –

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包。