Structured writing to console, such as a table

Bob Gailer bgailer at alum.rpi.edu
Mon Sep 1 21:19:20 EDT 2003


At 02:37 PM 9/1/2003 -0500, Raaijmakers, Vincent (IndSys, GE Interlogix) wrote:

>Ok, perhaps a question on a newbie level.
>
>I try to create a simple 'write to a console application' where all the 
>items in a string
>do have a variable size:
>items = ["a", "bbbbbbbbb", "cc"]
>Well, actually, I need to print a table as simple text, nice lined up in a 
>console.
>So:
>
>
>Item:       Value:     Another Value:
>----------+----------+------------------
>a         | 1        | 2
>bbbbbbbbb | 2        | 17
>cc        | 3        | 5
>
>My hope was that somewhere in python land an existing module was waiting 
>for me.
>A module that also prints lines, headers....
>
>Unfortunately, I can't find it. Books, Google...
>Before I reinvent this wheel... please give me some tips, references, 
>examples...

In addition to other responses, consider this which uses nested % 
formatting to make format strings for reuse:

class Table:
   seps = '- +|'
   def __init__(self, *columnWidths):
     if columnWidths:
       self.setWidths(columnWidths)
   def setWidths(self, columnWidths):
     self.columnWidths = columnWidths
     format1 = ("%%%%-%ss%%s"*len(columnWidths))[:-3]
     format2 = format1 % columnWidths
     self.nSeps = len(columnWidths) - 1
     self.hdrFormat = format2 % ((self.seps[1], )*self.nSeps)
     self.sepFormat = format2 % ((self.seps[2], )*self.nSeps)
     self.rowFormat = format2 % ((self.seps[3], )*self.nSeps)
   def printHdr(self, *heading):
     print self.hdrFormat % heading
   def printSep(self):
     print self.sepFormat % tuple([self.seps[0]*w for w in self.columnWidths])
   def printRow(self, *items):
     print self.rowFormat % items
print

tbl = Table(12, 12, 16)
tbl.printHdr('Item:', 'Value:', 'Another Value:')
tbl.printSep()
tbl.printRow('a', 1, 2)
tbl.printRow('bbbbbbb', 2, 17)
tbl.printRow('cc', 3, 5)


Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003


More information about the Python-list mailing list