<p>按制表符格式化在历史上是很棘手的。一旦某个字段的长度超过tabstep,整个格式就会中断。在本例中,该字段是头<code>"payment"</code>。在</p>
<p>不使用制表符,您可以计算列宽(以字符为单位)并创建匹配的<code>str.format</code>格式。我假设你有类似的数据</p>
<pre><code>data = [(1, 500, 416.67, 99916.67),
(2, 500, 416.32, 99832.99),
...]
header = [("month", "payment", "interest", "balance")]
</code></pre>
<p>正在打印:</p>
^{pr2}$
<p>相反,您将需要额外的时间运行数据。一次确定列宽,然后打印一次。在</p>
<pre><code>colwidths = []
for column in zip(*(header + data)):
colwidths.append(len(str(max, column, key=lambda s: len(str(s)))) + 1)
# the `+ 1` in this case being the column margin
formatting = "".join(r"{{:{}}}".format(width for width in colwidths))
for line in header + data:
print(formatting.format(*line))
</code></pre>
<hr/>
<p>或者,您可以让<code>tabulate</code>为您做这项工作。这是保存在pypi包管理器<a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">here</a>中的第三方模块。安装时</p>
<pre><code>pip install tabulate
</code></pre>
<p>然后使用如下代码:</p>
<pre><code>import tabulate
data = [(1, 500, 416.67, 99916.67),
(2, 500, 416.32, 99832.99),
...]
header = [("month", "payment", "interest", "balance")]
print(tabulate.tabulate(data, headers=*header))
</code></pre>