1

私はPythonを使用して、リストの内容を1行ずつ出力しています:

header = ['State', 'AVG Loan Size', 'AVG Interest Rate', 'AVG Loan Duration']
widths = [ len(col) for col in header ]
print '{}\t{}\t{}\t{}'.format(*(header + widths))
for line in output:
    print '{0:^{4}}\t{1:^{5},.0f}\t{2:^{6},.1f}\t{3:^{7},.0f}'.format(*(line + widths))

これは私にこれを与えます:

State   AVG Loan Size   AVG Interest Rate   AVG Loan Duration
 CA        10,651             12.1                 41        
 TX        10,692             12.1                 42        
 VA        10,693             12.1                 42        
 GA        10,675             12.1                 42 

ここで、2 番目の列の先頭にドル記号を配置し、最後の列の最後に「月」を配置したいと考えています。どうすればこれを達成できますか?単なる置換ではなく、リテラル文字を連結した置換の幅とセンタリングを定義する必要があります。

たとえば、次のコードは機能しません。

print '{0:^{4}}\t${1:^{5},.0f}\t{2:^{6},.1f}\t{3:^{7},.0f} months'.format(*(line + widths))

結果は次のようになります (「$」と「月」がセンタリングに含まれていないことに注意してください:

State   AVG Loan Size   AVG Interest Rate   AVG Loan Duration
 CA     $   10,651            12.1                 41         months
 TX     $   10,692            12.1                 42         months
 VA     $   10,693            12.1                 42         months
 GA     $   10,675            12.1                 42         months
4

1 に答える 1