string interpolation syntactic sugar

Skip Montanaro skip at mojam.com
Fri Dec 10 11:27:18 EST 1999


Referring to

    "a %(x)s b %(y)s" % locals()
and
    "a %(x)s b %(y)s" % obj.__dict__

Hartmut asks:

    How efficient is this?

Efficient enough. ;-)

Seriously, it's pretty fast (it's essentially just sugar coated sprintf),
and faster (and more readable) than the other obvious alternatives, like

    "a " + `x` + " b " + `y`

and I imagine only slightly slower than the tuple-based interpolation:

    "a %s b %s" % (x, y)

which gets to a maintenance nightmare if you have lots of substitutions to
perform.  Suppose you have

    "the %s %s %s jumped over the %s %s" % (x, y, z, i, j,)

and you wanted to add a new format specifier.  You have to count format
elements from the beginning of the format string to the point at which you
want the new % thingie, then do the same in the tuple of substitution
values.  An error-prone exercise, to be sure, especially if the values are
more complex (function calls with multiple arguments, yadda, yadda, yadda).

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list