How can I specify the amount of spaces between columns by using tabulate module in python

5.8k views Asked by At

Id like to know if there is some argument I can pass to tabulate module and specify the quantity of empty spaces between columns.

I can see there are 2 spaces by default but I didnt find how do manipulate that. This is script example.

from tabulate import tabulate

data = [
  ["Name","LastName", "Age"],
  ["Juan","Lopez", "22"],
  ["Luisa","Perez", "24"],
  ["Ana","Sanchez", "23"]
]

print (tabulate(data, stralign="right", tablefmt="plain"))

Output:

 Name  LastName  Age
 Juan     Lopez   22
Luisa     Perez   24
  Ana   Sanchez   23

The complete task is about extract data from a plan text and organize it. One way I did to solve the problem was adding empty columns between each data column but maybe is not the most eficcient way.

3

There are 3 answers

2
GregoirePelegrin On

As far as I can tell, tabulate doesn't seem to have an argument for this. Maybe look into prettytable, and especially the "Changing the appearance of your table - the hard way" chapter, that allows you to be more flexible with the table style.

EDIT: texttable may be useful too, as you can define the column width. The documentation seems to be a bit lacking though, and while the ease of use may be better, the modularity seems to be a bit worse at first glance.

3
Shikeagle On

I know this is an older post, but could you not use whitespace to extend the cell?

Text formatting By default, tabulate removes leading and trailing whitespace from text columns. To disable whitespace removal, set the global module-level flag PRESERVE_WHITESPACE:

import tabulate tabulate.PRESERVE_WHITESPACE = True

Tabulate on PyPI

1
Ross Smith II On

I was able to reduce the column separator width to a single character with:

tablefmt = "minpadding"
tabulate._table_formats[tablefmt] = tabulate.TableFormat(
  lineabove=tabulate.Line("", "-", " ", ""),
  linebelowheader=tabulate.Line("", "-", " ", ""),
  linebetweenrows=None,
  linebelow=tabulate.Line("", "-", " ", ""),
  headerrow=tabulate.DataRow("", " ", ""),
  datarow=tabulate.DataRow("", " ", ""),
  padding=0,
  with_header_hide=["lineabove", "linebelow"],
)
tabulate.multiline_formats[tablefmt] = tablefmt
tabulate.tabulate_formats = list(sorted(tabulate._table_formats.keys()))
rows = [
    ["Cell 1", "Cell 2"],
    ["Cell 3", "Cell 4a\nCell 4b"],
    ["Cell 5", "Cell 6"],
]
print(tabulate.tabulate(rows, headers="firstrow", tablefmt=tablefmt))

which produces:

Cell 1   Cell 2
-------- --------
Cell 3   Cell 4a
         Cell 4b
Cell 5   Cell 6