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))
使用format()。例如:
这里
^{pr2}$d
代表十进制整数,f
代表浮点数。数字就是宽度。{cd3>七位整数^表示宽度:和
15.2f
一个总宽度为15和2位小数的浮点数:输出示例:
是:
按制表符格式化在历史上是很棘手的。一旦某个字段的长度超过tabstep,整个格式就会中断。在本例中,该字段是头
"payment"
。在不使用制表符,您可以计算列宽(以字符为单位)并创建匹配的
str.format
格式。我假设你有类似的数据正在打印:
^{pr2}$相反,您将需要额外的时间运行数据。一次确定列宽,然后打印一次。在
或者,您可以让
tabulate
为您做这项工作。这是保存在pypi包管理器here中的第三方模块。安装时然后使用如下代码:
相关问题 更多 >
编程相关推荐