Python 使用.format()将非替换的内容居中
我使用python逐行打印列表的内容,如下所示:Python 使用.format()将非替换的内容居中,python,formatting,format,Python,Formatting,Format,我使用python逐行打印列表的内容,如下所示: 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
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
我现在想在第二列的开头加上一个美元符号,在最后一列的末尾加上几个月符号。我怎样才能做到这一点?我不仅需要为替换定义宽度和居中,还需要为用文字字符连接的替换定义宽度和居中
例如,此代码不起作用:
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
如果看不到line和width变量的原点,我无法确定,但似乎是将表元素插入到带有填充的字符串中,然后添加$and months。尝试将$and months包含在使用format插入的原始表元素中。换句话说,保持打印语句与第一个建议中的原样,然后对线条/宽度变量进行更改 你能告诉我们线条和宽度变量是从哪里来的吗?我考虑过这个问题,但是我需要将10651.0281更改为“$10651”,最后需要进行两轮格式化。那当然行,但看起来并不优雅。我不知道,我不认为这是特别不公平的。。简单地说$+strloan我真的不认为有比这更优雅的方法。。