如何在 Python 中使用 Tabulate 保留至少 15 个空格来居中对齐数据

How to center align data with at least 15 spaces reserved with Tabulate in Python

如何打印一个 table 每个字段都有 15 个空格并且这些字段中的数据也必须居中?

像这样:


        Name              Address      
--------------------  ---------------
        Abcd               Abcd
12345678901234567890       Abcd

您可以使用 formatting、join 和列表理解:

headers = ['Name', 'Address']
value_lines = [
    ['Abcd', 'Abcd'],
    ['12345678901234567890', 'Abcd']
]

print(' '.join(['{:^25s}'.format(h) for h in headers]))
print(' '.join('-' * 25 for i in range(len(headers))))
for value_line in value_lines:
    print(' '.join(['{:^25s}'.format(value) for value in value_line]))

输出:

          Name                     Address         
------------------------- -------------------------
          Abcd                      Abcd           
  12345678901234567890              Abcd           

如果需要根据所有值增加列宽,可以这样:

headers = ['Name', 'Address']
value_lines = [
    ['Abcd', 'Abcd'],
    ['12345678901234567890', 'Abcd']
]

column_widths = [15] * len(headers)
for i, header in enumerate(headers):
    column_widths[i] = max(column_widths[i], len(header))
for value_line in value_lines:
    for i, value in enumerate(value_line):
        column_widths[i] = max(column_widths[i], len(value))

print(' '.join([
    ('{:^' + str(column_widths[i]) + 's}').format(h)
    for i, h in enumerate(headers)
]))
print(' '.join('-' * column_widths[i] for i in range(len(headers))))
for value_line in value_lines:
    print(' '.join([
        ('{:^' + str(column_widths[i]) + 's}').format(value)
        for i, value in enumerate(value_line)
    ]))

输出:

        Name             Address    
-------------------- ---------------
        Abcd              Abcd      
12345678901234567890      Abcd