使用制表符在Python中打印表格时列对齐不正确

4

我想打印一张带有标签的表格,当标签长度较短时,一切都很好;但是当标签很长时,列就不匹配了!

我使用制表符来制造空格。这是代码:

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坐标X坐标向外推了!我该怎么让它们对齐呢?


“print” 不会检查字符串中的字符数量,因此不会对它们进行对齐。 - Fourier
制表符会在预定义的制表位上对齐(通常是每8个字符加1个)。如果所写文本超过下一个制表位,则后续制表符将向前对齐到下一个制表位,而不考虑光标已经在行中的位置。制表符一直以这种方式运作。 - tonypdmtr
4个回答

2

一种可能的解决方案是依赖于一些专门为此目的设计的软件包,例如 tabulate了解更多!

请记住,您需要使用例如 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"))

1

除非字符串长度相同,否则不要使用 \t 进行对齐。

Python 3.6.4 (default, Jan 03 2018, 13:52:55) [GCC]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: table = """
   ...: \tX Coordinate\tY Coordinate\tResult
   ...: \t00\t00\t00
   ...: \t00\t00\t00
   ...: \t00\t00\t00
   ...: """

In [9]: def reformat(s):
   ...:     ss = s.strip().split('\n')
   ...:     tb = [i.strip().split('\t') for i in ss]
   ...:     length = max(max(len(w) for w in words) for words in tb) + 4
   ...:     return '\n'.join(''.join(f'{w:{length}}' for w in words) for words in tb)
   ...: 
   ...: 

In [10]: print(reformat(table))
X Coordinate    Y Coordinate    Result          
00              00              00              
00              00              00              
00              00              00  

1

这是一个关于Python字符串格式化的好资源。使用.format方法,您可以使用填充来对齐所有字符串:

header = ['X Coordinate', 'Y Coordinate', 'Result']
row = ['00', '00', '00']
rows = [header, row, row, row]
print('\n'.join([''.join(['{:16}'.format(x) for x in r]) for r in rows]))
#X Coordinate    Y Coordinate    Result          
#00              00              00              
#00              00              00              
#00              00              00

或者,使用 f-strings:

print('\n'.join([''.join([f'{x:16}' for x in r]) for r in rows]))

你也可以使用右对齐(注意格式字符串中的':>16'):
print('\n'.join([''.join([f'{x:>16}' for x in r]) for r in rows]))
#    X Coordinate    Y Coordinate          Result
#              00              00              00
#              00              00              00
#              00              00              00

基本上,将你的数据放入一个列表的列表中,然后决定所需的行宽,你就可以使用上面的单行代码来漂亮地打印出东西。


1
另一种方法是使用tabulate。
首先,您需要导入它。在网上搜索如何导入。 如果您像我一样使用Spyder,则在Anaconda的命令窗口中,只需键入:
conda install -c conda-forge tabulate

这非常有用!

table = [["X Coordinate", "Y Coordinate", "Result"], [00, 00, 00], [00, 00, 00], [00, 00, 00]]
print(tabulate(table))

这将产生以下结果:
------------  ------------  ------
X Coordinate  Y Coordinate  Result
0             0             0
0             0             0
0             0             0
------------  ------------  ------

或者你可以这样做:

table = [[00, 00, 00], [00, 00, 00], [00, 00, 00]]
print(tabulate(table, headers=["X Coordinate", "Y Coordinate", "Result"]))

这将产生以下结果:
  X Coordinate    Y Coordinate    Result
--------------  --------------  --------
             0               0         0
             0               0         0
             0               0         0

如果您不喜欢破折号,您可以使用这个替代方案:
print(tabulate(table, tablefmt="plain"))

然后将会产生以下结果:
X Coordinate  Y Coordinate  Result
0             0             0
0             0             0
0             0             0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接