Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Formatting
#1
Hi, I am trying to get the following columns to be formatted so that they are parallel instead of the numbers being off-centered from one another, and the second column needs to be formatted as money. I also need the total to be displayed in a parallel column at the bottom.
 champs = ("Cubs 2016 World Series","Blackhawks 2015 Stanley Cup","White Sox 2005 World Series","Bulls 1998 NBA Championsip","Bears 1985 Super Bowl")
tickprice = (4700,2200,1200,45,60)
total = 0
count = 0
for element in tickprice:
    total = element + total
count = 0
for thing in champs:
    print (thing, "${:>30.2f}".format(tickprice[count]))
    count = count + 1
Reply
#2
Parallel in a column? Do you want the right side, left side or center to be aligned? I don't know how to do center, but left or right justified is easy, and making columns line up comes down to formatting to the widest value.

In this example the team/event is left justified and the ticket price right justified. You need to specify a width for each column. Your second column was ragged as soon as you printed "thing" without specifying width.
champs = (
    "Cubs 2016 World Series",
    "Blackhawks 2015 Stanley Cup",
    "White Sox 2005 World Series",
    "Bulls 1998 NBA Championsip",
    "Bears 1985 Super Bowl")
 
tickprice = (4700,2200,1200,45,60)
total = sum(tickprice)
 
for champ, price in zip(champs, tickprice):
    # Can we embed a f string inside a fstring?  Still wouldn't do the minus sign
    if price < 0:  # Highly unlikely
        dollars = f'-${-price:.2f}'
    else:
        dollars = f'${price:.2f}'
    print(f'{champ:30s} {dollars:>8s}')

print('-'*39)
dollars = f'${total:.2f}'
print(f'{"Total for all events is":30s} {dollars:>8s}')
My first use of the zip function!
Reply
#3
If you're doing lots of columns, I often prefer to use a tool to set up the table for output rather than rolling my own formats. Tabulate is one such (and it's fairly simple), but there are many others.
Reply
#4
And usually if you are making tables, or at least big tables, you are using a package that knows how to print tables with pretty column headings and the like. If you don't have some "import"s at the top of the file you are doing too much typing and too little research.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020