rawsontetley.org

ASCIItable

I found myself in need of a simple way to print an ASCII/text table from a list of lists in Python.

There seem to be a few solutions out there, such as PrettyTable, which I’m sure are perfectly good.

They’re also quite big, full featured and involve adding another dependency to your project. I like having a simple module file that I can drop into my code and use, so that’s what I wrote.

from asciitable import ascii_table

print( ascii_table( [
        [ "Description", "Amount", "More" ],
        [ "Stringy", "0.52", "£0.58" ],
        [ "Another Rather Long Value", "£52.38", "20.00" ]
    ]))

produces:

Description               | Amount | More
--------------------------------------------
Stringy                   |   0.52 | £0.58
Another Rather Long Value | £52.38 | 20.00

You can also pass the column separator as an argument, along with if you would like columns containing numbers to be right-aligned instead of left (the default).

from asciitable import ascii_table

print( ascii_table( [
        [ "Description", "Amount", "More" ],
        [ "Stringy", "0.52", "£0.58" ],
        [ "Another Rather Long Value", "£52.38", "20.00" ]
    ], separator="   ", number_alignment="left" ))

produces:

Description                Amount  More
-----------------------------------------
Stringy                    0.52    £0.58
Another Rather Long Value  £52.38  20.00

Download