如何消除Python tabulate的rounded_outline格式列额外空格?
如何用tabulate生成紧凑格式的表格?
问题描述
执行以下Python代码使用tabulate库生成表格时:
rows = [ ["A1", "B2"], ["C3", "D4"], ["E5", "E6"], ] print(tabulate(rows, headers="firstrow", tablefmt='rounded_outline'))
得到的表格每个单元格带有额外空格,输出如下:
╭──────┬──────╮ │ A1 │ B2 │ ├──────┼──────┤ │ C3 │ D4 │ │ E5 │ E6 │ ╰──────┴──────╯
希望调整为紧凑格式:
╭────┬────╮ │ A1 │ B2 │ ├────┼────┤ │ C3 │ D4 │ │ E5 │ E6 │ ╰────┴────╯
解决方法
tabulate默认的rounded_outline格式会给每个单元格左右各添加1个空格(padding),要实现紧凑格式,只需自定义一个表格格式,将padding设置为0即可:
from tabulate import tabulate, TableFormat, Line, DataRow # 定义紧凑版的rounded_outline格式 compact_rounded_outline = TableFormat( lineabove=Line("╭", "─", "┬", "╮"), linebelowheader=Line("├", "─", "┼", "┤"), linebetweenrows=None, linebelow=Line("╰", "─", "┴", "╯"), headerrow=DataRow("│", "│", "│"), datarow=DataRow("│", "│", "│"), padding=0, # 移除单元格左右的默认空格 with_header_hide=None, ) rows = [ ["A1", "B2"], ["C3", "D4"], ["E5", "E6"], ] print(tabulate(rows, headers="firstrow", tablefmt=compact_rounded_outline))
运行上述代码后,就能得到目标中的紧凑表格。
内容的提问来源于stack exchange,提问作者gsxr1300
相关产品推荐
相关产品推荐

