ascii tables

Peter Hansen peter at engcorp.com
Thu May 29 14:27:43 EDT 2003


John Hunter wrote:
> 
> I often need to print several equal length, homogeneous lists (some
> lists are strings, some ints, some floats), and I would like to make a
> nice ascii table for display, with configurable format strings for
> each column, row and column separators etc....  Anyone know of some
> code that does this?

Not existing code, but it doesn't sound too hard.

Here are some ideas (untested):

>>> colSep = ','
>>> rowSep = '\n'
>>> formats = ['%-10s', '%10.3f', '%35s']

>>> data = [
    [ 'test', 55.6, 'a longer string' ],
    [ 'label', 3.14, 'extra data' ],
    [ 'another', 0, 'this is not a long string'],
    ]

>>> lineFmt = colSep.join(formats)
>>> print rowSep.join([lineFmt % tuple(line) for line in data])

test      ,    55.600,                    a longer string
label     ,     3.140,                         extra data
another   ,     0.000,          this is not a long string

(Okay, I lied.  I tested it after all. :-)

-Peter




More information about the Python-list mailing list