Programmer XYZ
Programmer XYZ

Reputation: 408

Aligning Separate Parts of Print

I am trying to align the text in my output.

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)

... and I want it to look like this when it is run.

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

The only way I've found to do this is extremely complex for something that should be fairly easy.

Problem solved, Thanks!

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

Upvotes: 1

Views: 124

Answers (2)

detly
detly

Reputation: 30332

You can just use the built-in string formatting:

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

...etc.

Breaking this down:

  • {item} means format the parameter named item
  • {item:20} means the formatted result should have width 20 characters
  • {price:>10.2f} means right align (>), width of 10 (10), floating point precision of 2 decimal places (.2f)

Incidentally, you might want to look at the Decimal package for currency work.

Upvotes: 1

Omnikrys
Omnikrys

Reputation: 2558

String ljust, rjust, center are what you want for padding a string like that.

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

Upvotes: 3

Related Questions