Printing tabular data in Python

Makis picture Makis · Feb 25, 2011 · Viewed 17.1k times · Source

What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like

for val1 in my_dict:
   for val2 in my_dict:
    if val1['a'] > val2['a']:
      print 'x'

but in such a way that each column is fixed width. Writter and formatter classes seem like something in the realm of possibility, but still look complex to use when compared to, say, Perl's formatter.

Are there any existing implementations or do I have to write my own?

Answer

Andreas Jung picture Andreas Jung · Feb 25, 2011
print "%20s" % somevar 

Will print the value 'somevar' and use up to 20 spaces. Add a comma behind the print statement in order to avoid the line-break - and of course: read the string formatting operations docs on the '%' operator