我想打印一张顶部带有一些标签的表格。当标签长度较短时,一切都很好;但是当标签很长时,列就会不匹配!
我正在使用制表符来腾出空间。这是代码:
table = """
\tX Coordinate\tY Coordinate\tResult
\t00\t00\t00
\t00\t00\t00
\t00\t00\t00
"""
print(table)
输出:
X Coordinate Y Coordinate Result
00 00 00
00 00 00
00 00 00
可以看到,Y Coordinate
已经被X Coordinate
推出了!我如何让它匹配!
最佳答案
一个可能的解决方案是依赖一些为此目的而设计的包,比如制表:Read more about it!
请记住,您必须使用例如pip install tabulate
from tabulate import tabulate
print tabulate([[00, 00, 00], [00, 00, 00], [00, 00, 00]], headers=['X Coordinate','Y Coordinate','Result'], tablefmt='orgtbl')
或者将您的原始表格与此代码一起使用:
alignment = len(max(table.split("\t")))+1
for line in table.strip().split("\n"):
row ="{{:>{}}}".format(alignment) * len(line.strip().split("\t"))
print row.format(*line.strip().split("\t"))
关于python - 使用制表符在 Python 中打印表格时列对齐不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50719744/