【问题标题】:Formatting the output in Python 2.7在 Python 2.7 中格式化输出
【发布时间】:2016-04-13 12:58:22
【问题描述】:

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

我的代码:

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'来调整输出但无法调整它...

任何帮助将不胜感激。 谢谢

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    我建议您使用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 
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多