0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.