[Tutor] Help with strings and lists.

John Fouhy john at fouhy.net
Fri Jul 14 06:43:32 CEST 2006


On 14/07/06, Alan Collins <online330983 at telkomsa.net> wrote:
> You now want columns 1, 5, and 7 printed and aligned (much like a
> spreadsheet). For example:
>
> Monday    547757699 100%
> Wednesday     77449 100%

Let me attempt to be the first to say:

String substitutions!!!

The docs are here: http://docs.python.org/lib/typesseq-strings.html

At their simplest, you can do things like:

s = '%s || %s || %s' % (columns[0], columns[4], columns[6])

This will print:

    Monday || 547757699 || 100%

Next, you can specify padding as well:

s = '%12s || %12s || %5s' % (columns[0], columns[4], columns[6])

and the first string will be padded with spaces to 12 characters, the
second to 12, and the last to 5.  You can change which side it pads on
by specifying negative field widths --- eg, %-12s instead of %12s.
(one will produce "      Monday", the other "Monday      ".  I forget
which.)

Next, you can tell python to read the field width from a variable:

s = '%*s || %*s || %*s' % (12, columns[0], 12, columns[4], 5, columns[6])
(ie: width first)

So all you need to do is find the maximum field width (have a look at
list comprehensions and the max() function), then use string
formatting operators to lay everything out :-)

-- 
John.


More information about the Tutor mailing list