Variables in strings..

Andrew Dalke dalke at acm.org
Mon Jul 24 21:00:45 EDT 2000


Gabriel Ambuehl wrote
>Perhaps. But in real world (tm) CGI scripts, one needs more than just
>one variable in there. I've got Perl scripts who insert aroun 40
>variables (including array slices) during one print <<"EOF"
>instruction. I could live with the "%(myvar)" % vars() syntax if there
>would be a possibility to reference to lists and dictionary entries as
>well. Without it, it's a real pain to quickly write CGI scripts.
>Hell,
>content='<tr> <td> <a href="http://'+ pair[0] + '">' + pair[0]+ '</a> </td>
<td>' + pair[1] + '</td><td><a href="' + PathToScript
>etc is nothing I can consider readably. (though pair1=pair[1]
>and pair2=pair[2] would do the job but that's not really what I'd
>consider elegant...)

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)

>>> a = LookupConverter({"name": "Andrew", "pair": [1, 4]})
>>> "I am 4(name)s.  The pairs are %(pair[0])d and %(pair[1])d" % a
'I am Andrew.  The pairs are 1 and 4'
>>>

You can even be really evil and do things like get the calling context
and lookup up the local and global variables, so you don't have to pass
in names.  But that wouldn't be very clean code - too magic for my
tastes.  Instead, try

>>> import math
>>> name = "Andrew"
>>> vals = [6, 4, 2]
>>> a = LookupConverter(locals())
>>> "name is %(name)s, vals[1] is %(vals[1])s, and pi == %(math.pi)f" % a
'name is Andrew, vals[1] is 4, and pi == 3.141593'

                    Andrew
                    dalke at acm.org

                    Andrew






More information about the Python-list mailing list