Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Print "Pretty" String Output in Python

I have a list of dicts with the fields classid, dept, coursenum, area, and title from a sql query. I would like to output the values in a human readable format. I was thinking a Column header at the top of each and then in each column the approrpiate output ie:

CLASSID     DEPT     COURSE NUMBER        AREA     TITLE foo         bar      foo                  bar      foo yoo         hat      yoo                  bar      hat 

(obviously with standard alignment/spacing)

How would I accomplish this in python?

like image 815
themaestro Avatar asked Feb 22 '11 22:02

themaestro


People also ask

How do I print pretty data in Python?

Import pprint for use in your programs. Use pprint() in place of the regular print() Understand all the parameters you can use to customize your pretty-printed output. Get the formatted output as a string before printing it.

What is Pprint Python?

Short for Pretty Printer, pprint is a native Python library that allows you to customize the formatting of your output.

How do you print nice columns in Python?

To create nice column output in Python, we can use format strings with print . We use the {: >20} to set each column to have at least 20 characters and align the text to the right. from the print output.


2 Answers

Standard Python string formatting may suffice.

# assume that your data rows are tuples template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10 print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header for rec in your_data_source:    print template.format(*rec) 

Or

# assume that your data rows are dicts template = "{CLASSID:8}|{DEPT:10}|{C_NUM:15}|{AREA:7}|{TITLE:10}" # same, but named print template.format( # header   CLASSID="CLASSID", DEPT="DEPT", C_NUM="COURSE NUMBER",    AREA="AREA", TITLE="TITLE" )  for rec in your_data_source:    print template.format(**rec) 

Play with alignment, padding, and exact format specifiers to get best results.

like image 190
9000 Avatar answered Sep 22 '22 22:09

9000


class TablePrinter(object):     "Print a list of dicts as a table"     def __init__(self, fmt, sep=' ', ul=None):         """                 @param fmt: list of tuple(heading, key, width)                         heading: str, column label                         key: dictionary key to value to print                         width: int, column width in chars         @param sep: string, separation between columns         @param ul: string, character to underline column label, or None for no underlining         """         super(TablePrinter,self).__init__()         self.fmt   = str(sep).join('{lb}{0}:{1}{rb}'.format(key, width, lb='{', rb='}') for heading,key,width in fmt)         self.head  = {key:heading for heading,key,width in fmt}         self.ul    = {key:str(ul)*width for heading,key,width in fmt} if ul else None         self.width = {key:width for heading,key,width in fmt}      def row(self, data):         return self.fmt.format(**{ k:str(data.get(k,''))[:w] for k,w in self.width.iteritems() })      def __call__(self, dataList):         _r = self.row         res = [_r(data) for data in dataList]         res.insert(0, _r(self.head))         if self.ul:             res.insert(1, _r(self.ul))         return '\n'.join(res) 

and in use:

data = [     {'classid':'foo', 'dept':'bar', 'coursenum':'foo', 'area':'bar', 'title':'foo'},     {'classid':'yoo', 'dept':'hat', 'coursenum':'yoo', 'area':'bar', 'title':'hat'},     {'classid':'yoo'*9, 'dept':'hat'*9, 'coursenum':'yoo'*9, 'area':'bar'*9, 'title':'hathat'*9} ]  fmt = [     ('ClassID',       'classid',   11),     ('Dept',          'dept',       8),     ('Course Number', 'coursenum', 20),     ('Area',          'area',       8),     ('Title',         'title',     30) ]  print( TablePrinter(fmt, ul='=')(data) ) 

produces

ClassID     Dept     Course Number        Area     Title                          =========== ======== ==================== ======== ============================== foo         bar      foo                  bar      foo                            yoo         hat      yoo                  bar      hat                            yooyooyooyo hathatha yooyooyooyooyooyooyo barbarba hathathathathathathathathathat 
like image 35
Hugh Bothwell Avatar answered Sep 23 '22 22:09

Hugh Bothwell