sprintf behaviour

Alex Martelli aleax at aleax.it
Sat Feb 22 12:07:52 EST 2003


Carl Banks wrote:
   ...
> Yes.  What you need to do is define a function such as byindex below;
> this takes a tuple and turns it into a dict where the keys are the
> stringized tuple indices:
> 
>     def byindex(t):
>         n = len(t)
>         r = map(str,xrange(n))
>         return dict(zip(r,t))
> 
> Because the Python % operator can accept a dict, you can use this to
> get the effect you seek, like this:
> 
>     >>> print "--- %(1)s --- %(0)s ---" % byindex(('a', 'b'))

Neat idea!  Note that % can accept any _mapping_, so an alternate
but equivalent approach would be:

class byindex:
    def __init__(self, sequence):
        self.sequence = sequence
    def __getitem__(self, index):
        return self.sequence[int(index)]

to be used just as above; presumably helpful if you need to wrap
with "byindex" a potentially very long sequence of which perhaps
only a few items might be used in any given case.


> Note that 1 and 2 in the GCC example are replaced with 0 and 1 here; I
> did it that way because Python is strongly zero-based.  (I know C is
> too; but Python is, I would say, much more strongly zero-based.)
> 
> If you must use 1 and 2 instead of 0 and 1, you can change xrange(n)
> to xrange(1,n+1).

Similarly, in the "class byindex" approach you could achieve such
functionality by changing the body of __getitem__ to:

        return self.sequence[int(index)-1]


Alex





More information about the Python-list mailing list