I am trying to format a group of columns in python 3. So far I have not had much luck.
This is the code I am using.
first_row = ['Indicator',':Min',':Max']
col_width = max(len(word) for word in first_row) +20# padding
print ("".join(word.ljust(col_width) for word in first_row))
print('----------------------------------------------------------------------------')
heart=['Heart Disease Death Rate (2007)',stateheart_min(),heartdis_min(),stateheart_max(),heartdis_max()]
motor=[ 'Motor Vehicle Death Rate (2009)',statemotor_min(),motordeath_min(),statemotor_max(),motordeath_max()]
teen=['Teen Birth Rate (2009)',stateteen_min(),teenbirth_min(),stateteen_max(),teenbirth_max()]
smoke=['Adult Smoking (2010)',statesmoke_min(),adultsmoke_min(),statesmoke_max(),adultsmoke_max()]
obese=['Adult Obesity (2010)',stateobese_min(),adultobese_min(),stateobese_max(),adultobese_max()]
heart_col_width = max(len(word) for word in heart)
motor_col_width = max(len(word) for word in motor)
teen_col_width = max(len(word) for word in teen)
smoke_col_width = max(len(word) for word in smoke)
obese_col_width = max(len(word) for word in obese)
for heart, motor, teen, smoke, obese in zip(heart, motor, teen, smoke, obese ):
print('{heart:{heart_col_width}}:{motor:{motor_col_width}} {teen:{teen_col_width}{smoke: {smoke_col_width}}{obese:{obese_col_width}'.format(heart, motor, teen, smoke, obese ))
Instead of using tabs to try and align things, specify the actual width of each column in your format statement.
Something like this:
Tabs are not a great way to line columns up. Use fixed widths instead:
Note that I included the
:
colon in the string format; no need to pass in those colons with the lists.You could make the width dynamic here; calculate it from the widest value in the
r1
list for example:Here
label_width
is first interpolated into the{lwidth}
slot, setting the width when formatting the{label:..}
slot, etc. I used named slots rather than positional, because using proper names makes it easier to figure out what goes where.