[Tutor] A nicer output...

Jeff Shannon jeff@ccvcorp.com
Tue, 02 Apr 2002 09:43:07 -0800


>
> To output values, you can also use the "%" idiom:
>
>  >>> titi = 1
>  >>> toto = "truc"
>  >>> outputTemplate = "First value: %i - Second value: %s"
>  >>> print outputTemplate % (titi, toto)
> First value: 1 - Second value: truc
>
> This is useful to format output strings in a complex way. As you guess, %i
> is the placeholder for an integer and %s is a placeholder for a string.
> There are codes for other data types.

If you want your information in neat columns, you can modify this slightly.  Each
of those placeholders can take an optional numeric qualifier, and the formatting
will pad the string out to at least that many characters.

>>> breakfast = ['spam', 'eggs', 'bacon', 'baked beans']
>>> for food in breakfast:
...  print 'Eating %8s now' % food
...
Eating     spam now
Eating     eggs now
Eating    bacon now
Eating baked beans now
>>>

Note that extra space is added at the front of each food, so that %8s is printed
as *at least* eight characters.  But when there's more than 8 characters, it
doesn't truncate, just prints the whole thing as is.  If you wanted to have the
space added *after* each food, you can just make the number a negative, like so:

>>> for food in breakfast:
...  print 'Eating %-8s now' % food
...
Eating spam     now
Eating eggs     now
Eating bacon    now
Eating baked beans now
>>>

Now all the words are left-aligned instead of right-aligned.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International