[Tutor] Strings and the % Operator

Doug Stanfield DOUGS@oceanic.com
Wed, 15 Dec 1999 07:42:09 -1000


I'm trying to format some text to fit a box that is a variable width.
Because its not at all obvious to me where to find the string formatting
codes and the % operator in the Python documentation I'll ask here.  This
should illustrate what I need.  This was modeled on an example in the
'Tutorial':

[dougs@lawelawe pydev]$ python
Python 1.5.2 (#1, Apr 18 1999, 16:03:16)  [GCC pgcc-2.91.60 19981201
(egcs-1.1.1  on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> myString = "A bunch of stuff that exceeds 10 characters"
>>> otherString = "or not!"
>>> new1 = "[1: %-10s ]" % myString
>>> new1
'[1: A bunch of stuff that exceeds 10 characters ]'
>>> new2 = "[1: %-10s ]" % otherString
>>> new2
'[1: or not!    ]'

The second case does exactly what I want, but the first doesn't truncate.

>>> width = 10
>>> new3 = "[1: %-width s ]" % myString
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: unsupported format character 'w' (0x77)
>>>

I've no clue how to proceed with using a variable to format.

Regarding the documentation, the % operator doesn't appear in the index of
the 'Library Reference'.  The TOC has 'String Services' but it doesn't
appear there.  There is a reference in the index to 'operator' but no %.
Its not the first time and won't be the last, but I'm confused.

-Doug-