打印数据在python中的列中右对齐

时间:2016-10-24 09:21:46

标签: string python-2.7

我有一个脚本,其列字段为:

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

我做了几个文件和数据处理并将字段打印为:

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)

输出如下:

-------------------------------------------------------------------------
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

但是,我希望数据在右侧对齐

-------------------------------------------------------------------------
         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

我正在使用python 2.7

1 个答案:

答案 0 :(得分:1)

我建议阅读这个question的答案,因为我所做的只是修改了Sven Marnach的代码。

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)

row_format用于设置列宽和间距。更改17的值以使用不同数量的字符。 format(...)用于以正确的间距插入值。