Python 格式表格输出 [英] Python format tabular output
本文介绍了Python 格式表格输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 python2.7,我试图打印到屏幕表格数据.
Using python2.7, I'm trying to print to screen tabular data.
这大概是我的代码的样子:
This is roughly what my code looks like:
for i in mylist:
print "{}\t|{}\t|".format (i, f(i))
问题在于,根据i
或f(i)
的长度,数据不会对齐.
The problem is that, depending on the length of i
or f(i)
the data won't be aligned.
这是我得到的:
|foo |bar |
|foobo |foobar |
我想得到什么:
|foo |bar |
|foobo |foobar |
是否有任何模块允许这样做?
Are there any modules that permit doing this?
推荐答案
推出自己的格式化功能并不难:
It's not really hard to roll your own formatting function:
def print_table(table):
col_width = [max(len(x) for x in col) for col in zip(*table)]
for line in table:
print "| " + " | ".join("{:{}}".format(x, col_width[i])
for i, x in enumerate(line)) + " |"
table = [(str(x), str(f(x))) for x in mylist]
print_table(table)
这篇关于Python 格式表格输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文