Variables in strings..

Andrew Dalke dalke at acm.org
Thu Jul 27 12:18:10 EDT 2000


(horn tooting follows)

I wrote:
>You could write a wrapper, like:
>
>class LookupConverter:
>  def __init__(self, dict):
>    self.dict = dict
>  def __getitem__(self, name):
>    return eval(name, {"__builtins__": {}}, self.dict)
>

I should have shown the even more impressive

>>> import math
>>> lookup = LookupConverter(locals())
>>> "cos(45 degrees) == %(math.cos(math.pi/4))f" % lookup
'cos(45 degrees) == 0.707107'

Try doing *that* in Perl :)  But seriously, I am impressed that
this can be done at all, since it understands balanced parens,
although not quotes:

>>> "%(f('))', 9)s" % {}
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
KeyError: f(')

Is this a bug?

                    Andrew








More information about the Python-list mailing list