在Python 2.7中格式化输出

时间:2016-04-13 12:58:22

标签: python python-2.7

我在打印输出方面遇到了一些问题...

我的代码:

def main():
    total = 0
    capital = ["Bern", "London", "Washington D.C"]
    country = ["Switzerland", "England", "America"]
    population = [0.126,8.539,0.659]
    print "   Capital\tCountry\t\tPopulation"
    print "-------------\t-------------\t-------------"
    for i in range(len(capital)):
        print "%s\t%s\t%s"% (capital[i-1], country[i-1], population[i-1])
main()

输出:

   Capital      Country         Population
-------------   -------------   -------------
Washington D.C  America 0.659
Bern    Switzerland     0.126
London  England 8.539

我试图使输出看起来像这样:

   Capital         Country        Population
-------------   -------------   -------------
Washington D.C     America          0.659
Bern             Switzerland        0.126
London             England          8.539

我已经尝试了很多来通过添加和减少'\ t'来调整输出但是无法调整它...

非常感谢任何帮助。 感谢

2 个答案:

答案 0 :(得分:3)

我建议您使用str.format,如下所示,因为它有更好的文本格式和字符串调整以及所有可以使输出打印得更漂亮的东西:

>>> def main():
    capital = ["Bern", "London", "Washington D.C"]
    country = ["Switzerland", "England", "America"]
    population = [0.126,8.539,0.659]
    print '{:^15}{:^15}{:^15}'.format(*['Capital','Country','Population'])
    print '{:^15}{:^15}{:^15}'.format(*['-'*12]*3)
    for cap,cout,pop in zip(capital,country,population):
        print '{:<15}{:^15}{:^15}'.format(cap,cout,pop)


>>> main()
    Capital        Country      Population   
 ------------   ------------   ------------  
Bern             Switzerland       0.126     
London             England         8.539     
Washington D.C     America         0.659 

答案 1 :(得分:1)

%调用中为print运算符指定最小字段宽度。例如:

print "%24s" % ("Bern")