shanu
shanu

Reputation: 145

print data right aligned in column in python

I have a script which has a column field as:

States = ['Massachusetts', 'Pennsylvania','Utah','Ohio','California']

I do a couple of file and data processing and print the field as:

print '-'*200
print 'Name\tPopulation\tAverage Income\Crime Rate'
print '-'*200
for s in States:
    print '%s\t%s/%s\t%s\t%s' % (s, p_f, p_m, av, cr)

The output looks like:

-------------------------------------------------------------------------
Name    Population    Avergae Income    Crime Rate
-------------------------------------------------------------------------
Massachusetts    100000/100000    5000 50
Pennsylvania     100000/100000    5000 50
Utah 100000/100000    5000 50
Ohio 100000/100000    5000 50
California 100000/100000    5000 50

However, I would like data to be aligned right side

-------------------------------------------------------------------------
         Name       Population    Avergae Income    Crime Rate
-------------------------------------------------------------------------
Massachusetts    100000/100000              5000            50
 Pennsylvania    100000/100000              5000            50
         Utah    100000/100000              5000            50
         Ohio    100000/100000              5000            50
   California    100000/100000              5000            50

I am using python 2.7

Upvotes: 0

Views: 1376

Answers (1)

thialfi
thialfi

Reputation: 46

I would recommend reading the answer to this question because all I have done is modified Sven Marnach's code slightly.

states = ['Massachusetts', 'Pennsylvania','Utah','Ohio','California']
columns = ['Name', 'Population', 'Average Income', 'Crime Rate']

row_format = '{:>17}' * (len(columns))
print '-'*200
print row_format.format(*columns)
print '-'*200

for state in states:
    state_data = [p_f + '/' + p_m, av, cr]
    print row_format.format(state, *state_data)

The row_format is used to set up the column width and spacing. Change the value of the 17 to use a different number of characters. The format(...) is used to insert your values with the correct spacing.

Upvotes: 1

Related Questions