在Python 2.7中格式化输出
我在打印输出时遇到一些问题 我的代码:在Python 2.7中格式化输出,python,python-2.7,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 "-------
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”来调整输出,但无法调整它
任何帮助都将不胜感激。
谢谢在打印调用中为%操作员指定最小字段宽度。例如:
print "%24s" % ("Bern")
在打印调用中为%运算符指定最小字段宽度。例如:
print "%24s" % ("Bern")
我建议您使用,如下所示,因为它具有更好的文本格式和字符串调整,以及各种可以使输出打印得更漂亮的东西:
>>> 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
我建议您使用,如下所示,因为它具有更好的文本格式和字符串调整,以及各种可以使输出打印得更漂亮的东西:
>>> 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