percent string replacement with index

Matimus mccredie at gmail.com
Tue Jun 24 17:15:24 EDT 2008


On Jun 24, 12:26 pm, Terry Reedy <tjre... at udel.edu> wrote:
> Ulrich Eckhardt wrote:
> > What I'm surprised is that this isn't supported:
>
> >   "%(1)s %(2)s" % ("zero", "one", "two")
>
> > i.e. specifying the index in a sequence instead of the key into a map (maybe
> > I would use [1] instead of (1) though). Further, the key can't be a simple
> > number it seems, which makes this even more inconvenient to me.
>
> > Can anyone explain this to me?
>
> History.  See below.
>
>
>
> > Also, why isn't the 's' conversion (i.e. to a string) the default? I
> > personally would like to just write something like this:
>
> >   "%1 is not %2" % ("zero", "one", "two")
>
> > or maybe
>
> >   "%[1] is not %[2]" % ("zero", "one", "two")
>
> In 2.6 (I believe) and 3.0:
>
>  >>> "{1} is not {2} or {0}. It is just {1}".format("zero", "one", "two")


Or even:

>>> "{0[1]} is not {0[2]} or {0[0]}. It is just {0[1]}".format(["zero", "one", "two"])
'one is not two or zero. It is just one'

Or

>>> "{one} is not {two} or {zero}. It is just {one}".format(zero="zero", one="one", two="two")
'one is not two or zero. It is just one'

Or

>>> class C(object):
...     def __init__(self, zero, one, two):
...         self.zero = zero
...         self.one = one
...         self.two = two
...
>>> "{0.one} is not {0.two} or {0.zero}. It is just {0.one}".format(C("zero", "one", "two"))
'one is not two or zero. It is just one'

More information: http://www.python.org/dev/peps/pep-3101/

Exciting stuff.

Matt



More information about the Python-list mailing list