printing table on the command line

Daniel Dalton d.dalton at iinet.net.au
Thu Apr 29 04:03:22 EDT 2010


Hello,

I'm using the MySQLdb library in python to interface with a mysql
database I've created. I have written a command line app which runs from
the command line. I have 10 fields and hence, have found that each
record spreads over one line. What is the best way to print a table of a
database like this? Perhaps using tab spacing? Should I only print the
first 8 characters of each field, and allow the user to expand an
individual record? If so, how do I do this? I'm only new with python,
but %8s doesn't seem to do anything and with print it just prints the
number 8 before the string... 

I want to line up all the fields under the necessary headings, here is
the structure of the program:
for x in headings:
  print '%8s\t' % (x),
print '\n' # a few new lines
for x in records: # entire list of all records
  for i in x: # search individual record
    print '%8s\t' % (i),
  print '\n'

This may not be 100% exact, but I'm just trying to simplify it so I
don't need to paste the entire program here, note that records is a list
of all records in the table, and i is obviously a list of fields for
each individual record. Headings is just a tupple of strings such as
"name", "email" etc, just the name of the fields. 

So all I want to do is print a nicely formatted table to the screen on
the console, with tab spacing, I've got 10 fields per record, so will I
have to just chop off some characters?

Any examples of how to do this would be great, as I'm blind and it's a
bit difficult to check the spacing.

Thank you very much,
Dan



More information about the Python-list mailing list