Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Spacing/Formatting
#1
Hi!

I'm having some problems with spacing/formatting. I'm trying to get the pizza, state_tax, and pizza + state_tax outputs to start at directly under the 'H' in 'Here are the results:' and then have the numbers extend to the left. I tried <, >, and ^, but depending upon how big the pizza float is, the spacing doesn't match up. Any idea what I'm doing wrong?

Any help would be appreciated.
def main():
    name = 'Peter Tork'
    print('Welcome to Your Favorite Survey Program')
    print()
    print("Today we surveyed "+name+"."  "  Here are the results:")
    pizza = float(input ('11. If you order pizza, about how much would you pay before taxes? '))
    tax = float(0.065)
    state_tax = pizza * tax
    print(f'10. Pizza Cost: ${pizza:^34,.2f}')
    print(f'State Tax: ${state_tax:^34,.2f}')
    print(f'Pizza Total: ${pizza + state_tax:,.2f}')
main()
Reply
#2
I had more success with this
    print(f'{"10.Pizza Cost: $":<31}{pizza:.2f}')
    print(f'{"State Tax: $":<31}{state_tax:.2f}')
    print(f'{"Pizza Total: $":<31}{pizza + state_tax:.2f}')
Reply
#3
The problem is that the python format strings only deal with that one variable. And you want them to align properly also depending on the length of the text before them (like "Pizza Cost" or "State Tax").

There are modules out there that will do the alignment for you. You stick them in a table and it aligns the table.

With tabulate, you could do something like this:
    table = [['10. Pizza Cost:', pizza],
             ['State Tax:', state_tax],
             ['Pizza Total:', pizza + state_tax]]
    print(tabulate(table, floatfmt=".2f", tablefmt="plain"))
Output:
10. Pizza Cost: 34.50 State Tax: 2.24 Pizza Total: 36.74
But if you want to roll your own, you need to calculate the size of the preceding string and use that for your format object. Something like:

def force_align(string1, string2, min_width=50):
    """Given two strings, shove them together such that the
    minimum width is never less than min_width"""
    pad = min_width - len(string1)
    return f"{string1}{string2:>{pad}}"

print(force_align('10. Pizza Cost:', f'{pizza:.2f}'))
print(force_align('State Tax:', f'{state_tax:.2f}'))
print(force_align('Pizza Total:', f'{pizza + state_tax:.2f}'))
Output:
10. Pizza Cost: 34.50 State Tax: 2.24 Pizza Total: 36.74
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyplot line color and spacing/padding metalray 0 2,713 May-26-2017, 08:39 AM
Last Post: metalray

Forum Jump:

User Panel Messages

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