
April 19th, 2004, 05:05 AM
|
|
Contributing User
|
|
Join Date: Feb 2004
Location: London, England
|
|
From the Python docs (section 2.3.6.2):
Quote: A conversion specifier contains two or more characters and has the following components, which must occur in this order:
1. The "%" character, which marks the start of the specifier.
2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
3. Conversion flags (optional), which affect the result of some conversion types.
4. Minimum field width (optional). If specified as an "*" (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
5. Precision (optional), given as a "." (dot) followed by the precision. If specified as "*" (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
6. Length modifier (optional).
7. Conversion type. |
So from (4) above, you can pass a variable for the column width like this:
Code:
>>> maxlen = 10
>>> '|%*s|' % (maxlen, 'hello')
'| hello|'
>>> '|%-*s|' % (maxlen, 'hello') #use '-' to left justify
'|hello |'
Note that this does not work with using a dictionary and '%(name)s', since you have to pass the width in as part of a tuple.
Dave - The Developers' Coach
|