2016-04-13 3 views
1

のフォーマットは...私は出力を印刷するには、いくつかの問題を抱えています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 

私はトライを持っていますd \ 'を追加したり減らしたりして出力を調整することはたくさんありますが、調整することはできませんでした。

何か助けていただければ幸いです。 ありがとう

答えて

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

printコールで%オペレータに最小フィールド幅を指定してください。たとえば:

print "%24s" % ("Bern") 
関連する問題