printing table on the command line

Peter Otten __peter__ at web.de
Thu Apr 29 04:28:55 EDT 2010


Daniel Dalton wrote:

> 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.

You can limit the number of characters by adding a second number to the 
format string:

>>> column = "alpha"
>>> print ("%-3.3s" % column).replace(" ", "*")
alp

A minus added to the format string controls where the extra spaces are 
added:

>>> print ("%8.8s" % column).replace(" ", "*")
***alpha
>>> print ("%-8.8s" % column).replace(" ", "*")
alpha***

I've added the str.replace() call that replaces spaces with asterisks only 
to make it easier for you to find out where python adds spaces.

To process a list of columns use the str.join() method:

>>> headings = ["alpha", "beta", "a_very_loooong_heading"]
>>> print "\t".join("%-8.8s" % s for s in headings).replace(" ", "*")
alpha***        beta****        a_very_l

Peter



More information about the Python-list mailing list