Search code examples
pythoncsvalignmentspacingtabular

Can I create an aligned table with an if statement in python?


I have data from a CSV file that tells whether or not a basketball player is obese.

I need to make a perfectly aligned table from this data; I have all the information to tell whether or not a player is obese. However, I have an "if" statement that prints out the values of each obese player and I need to make this print out in neat, aligned rows.

I have:

obese_count = 0
total_count = 0


print (" " * 5, "First Name", " " * 2, "Last Name", " " * 2, "Height"," " * 2,"Weight"," " * 2, "BMI") # header
print ("- " * 20)
for player in players:
    if has_data(player):
        if is_obese(player):
            print (" " * 5, player["firstname"]," " * 5, player["lastname"]," " * 9, player["h_feet"]," " * 9,player["h_inches"]," " * 5, player["weight"])
            obese_count += 1
        total_count += 1

which is returning a very sloppy table:

      First Name    Last Name    Height    Weight    BMI
- - - - - - - - - - - - - - - - - - - - 
      Carlos       Boozer           6           9       280
      Elton       Brand           6           8       275
      Glen       Davis           6           9       289
      Thomas       Hamilton           7           2       330
      James       Lang           6           10       305
      Jason       Maxiell           6           7       280
      Oliver       Miller           6           9       280
      Craig       Smith           6           7       272
      Robert       Traylor           6           8       284
      Jahidi       White           6           9       290

I was wondering if there is any way I could tidy this up, so that I can have a neat and aligned table or at least aligned rows that aren't spaced out differently.


Solution

  • String formatting is your friend.

    For instance,

    print '{:<10} {:<10} {:>2}\' {:>2}" {:>6}'.format(player["firstname"], player["lastname"], player["h_feet"], player["h_inches"], player["weight"])
    

    This should return something like this:

    Carlos     Boozer      6'  9"    280
    Elton      Brand       6'  8"    275
    Glen       Davis       6'  9"    289
    

    As an aside: it looks like your table has a header for BMI, but there's not a corresponding field in your player dictionary.