Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking for a way to pretty-print tables like this:

======================= | column 1 | column 2 | ======================= | value1   | value2   | | value3   | value4   | ======================= 

I've found the asciitable library but it doesn't do the borders, etc. I don't need any complex formatting of data items, they're just strings. I do need it to auto-size columns.

Do other libraries or methods exist, or do I need to spend a few minutes writing my own?

like image 421
kdt Avatar asked May 06 '11 10:05

kdt


1 Answers

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).

like image 76
sastanin Avatar answered Sep 23 '22 08:09

sastanin