How can I pretty-print ASCII tables with Python? [closed]

I’ve read this question long time ago, and finished writing my own pretty-printer for tables: tabulate.

My use case is:

  • I want a one-liner most of the time
  • which is smart enough to figure the best formatting for me
  • and can output different plain-text formats

Given your example, grid is probably the most similar output format:

from tabulate import tabulate
print tabulate([["value1", "value2"], ["value3", "value4"]], ["column 1", "column 2"], tablefmt="grid")
+------------+------------+
| column 1   | column 2   |
+============+============+
| value1     | value2     |
+------------+------------+
| value3     | value4     |
+------------+------------+

Other supported formats are plain (no lines), simple (Pandoc simple tables), pipe (like tables in PHP Markdown Extra), orgtbl (like tables in Emacs’ org-mode), rst (like simple tables in reStructuredText). grid and orgtbl are easily editable in Emacs.

Performance-wise, tabulate is slightly slower than asciitable, but much faster than PrettyTable and texttable.

P.S. I’m also a big fan of aligning numbers by a decimal column. So this is the default alignment for numbers if there are any (overridable).

Leave a Comment