[Tutor] Formatting output into columns

Alan Gauld alan.gauld at btinternet.com
Thu Aug 30 23:44:03 CEST 2007


"Scott Oertel" <freebsd at scottevil.com> wrote

>> Use format strings. You can calculate the column widths by 
>> analyzing
>> the data then create a format string for the required number of
>> columns.
>> Finally insert the data on each row from a tuple.
>>
> Do you have any good documentation that could shed some more light 
> on
> exactly how to use format strings in such a way?

The docs contain the basic documentation, here is a short example:


data = ['one','fifteen',''four']

max_width = max([len(w) for w in data)])

# there's a slightly better way to do this which I can't recall right 
now!
# %% -> literal %,
# %s = insert string
# so %%%ss -> %Xs where X is the inserted data
fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width)

print fmtStr % tuple(data)

That should produce a format string where each column is the max width
of any of the data items

You can use the string center() method to pad the headings if 
required.
You can either put left/right justification into the format string 
(using +/-)
or use the string methods (rjust,ljust) to do it for you.

If its not clear how to extend that to a multi dimensional set of
data then feel free to ask for more detail with some sample data
and the specific requirements

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list