On 25/08/06, Vincent Gulinao <[EMAIL PROTECTED]> wrote:
> Anyone knows a neat way of displaying output in columnar/tabular form?
>
> Say you have a list with both dictionary and string members; you want to
> print the data, dictionary being one element per line, and the string on the
> next "column" aligned on the first element of the dictionary, or something
> like that.
If you want to DIY, have a look at string formatting (ie: the % operator).
I don't quite understand your example, so here's an (untested) example
of my own -- printing a list of strings in a table of 3 columns:
input = [ ... ] # list of strings
WIDTH = 3 # columns in the table
# split input up into tuples, ie: first 3, then next 3, then next 3, etc.
rows = [input[WIDTH*i:WIDTH*i+WIDTH] for i in range(len(input)//WIDTH + 1)]
# get max width of each column
widths = [max([row[i] for row in rows]) for i in range(WIDTH)]
for row in rows:
for i, s in enumerate(row):
print '%*s' % (widths[i], s),
print
The idea is to figure out what goes on each row of the table, then
calculate the maximum width of each column. Then
'%*s' % (w, s)
will be the string s, padded to width w.
(I always forget whether it gets padded on the left or on the right,
but you can always reverse it by adding a -: '%-*s' )
--
John.
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor