#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Posts
    9
    Rep Power
    0

    string formatting


    Suppose I have a list of words that i want to columnize. I can do

    for word in words:
    print "|%10s|%30s|" % (word, definition[word])

    to "columnize" the words. How can I do this if I want to dynamically feed in the column width? I can do:

    maxlen = 0
    for word in words:
    if (len(word) > maxlen):
    maxlen = len(word)

    To get the width I want, but then, I want to do something like:
    print "%(maxlen)s|" % (word)

    But this doesn't work because maxlen in this case is supposed to be a key to a hash (or something like that).

    Thanks,
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    From the Python docs (section 2.3.6.2):

    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

IMN logo majestic logo threadwatch logo seochat tools logo