0

Is there a way where I can right-align my output in such a way like this:

 Item: $  13.69
  Tax: $   5.30
  Oth: $   2.50  
---------------
Total: $  99.80  

Please note that I am using Python 3.

user1804933
  • 453
  • 2
  • 7
  • 14

3 Answers3

5

You can use the .format method of strings to do this:

fmt = '{0:>5}: ${1:>6.2f}'
print(fmt.format('Item', 13.69)) # Prints ' Item: $  13.69'
print(fmt.format('Tax', 5.3)) 
print(fmt.format('Oth', 2.5))
print('-'*len(fmt.format('Item', 13.69))) # Prints as many '-' as the length of the printed strings
print(fmt.format('Total', 99.8))
# etc...

The '{0:>5}' part is saying "take the zeroth item given to .format, and right justify it within 5 spaces". The '{1:>6.2f}' part is saying take the first item given to .format, right justify it within 6 spaces, formatting as a decimal with 2 decimal places.

Of course, in real code this would likely be part of a loop.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
0

You can use the same amount of spaces before the text with all of the items you want to align.

Another option would be to use the str.format operator as explained here.

Community
  • 1
  • 1
guyzyl
  • 387
  • 5
  • 18
0

Use string formatting:

print("$%6s" % dec_or_string)
Willem
  • 3,043
  • 2
  • 25
  • 37