[Tutor] Strings and the % Operator
Michael P. Reilly
arcege@shore.net
Wed, 15 Dec 1999 14:44:39 -0500 (EST)
[Charset iso-8859-1 unsupported, filtering to ASCII...]
> 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-
You want to look at section 2.1.5.1 "More String Operations" in the
Python Library Reference guide
<URL: http://www.python.org/doc/current/lib/typeseq-strings.html>.
It assumes some working knowledge of the string formatting used in C
and many similar systems.
What you want is the "*" directive:
>>> myString = "A bunch of stuff that exceeds 10 characters"
>>> fmt = '[1: %*.*s ]'
>>> # +--- first "*" - width
... # | +--- second "*" - precision
... # | | +--- "s"
... # v v v
...
>>> new1 = fmt % (-10, 10, myString)
>>> new1
'A bunch of'
>>>
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------