text processing: variable interpolation and more

Roman Suzi rnd at onego.ru
Sun Sep 9 07:58:20 CEST 2001

On Sun, 9 Sep 2001, Greg Weeks wrote:

>Many programs that I've written professionally create text files in various
>languages and formats.  Often, different invocations of the program create
>similar files.  In practice, I have needed both variable interpolation and
>conditional line inclusion in order to make these programs readable.  This
>is easy in Python, and I'd like to share the method below.  (There is
>nothing clever involved, and only 20 lines of code.)

>def render(f, string, globals, locals={}):
>    assert string and string[-1] == "\n", "string must end in newline"
>    def repl(mo, globals=globals, locals=locals):
>	if mo.group(1):			# VARIABLE WAS ESCAPED
>	    return  "<%s%s>" % (mo.group(1)[1:], mo.group(2))
>	else:				# THE USUAL CASE
>	    return  str(eval(mo.group(2), globals, locals))

Or you can use DocumentTemplate (from Zope) and write the whole
lot of things with Pythonish %()s-things. (sequencies are nice)

I tried many ways to do templating and found that probably
I just need XSLT. (Because usually information come in structured

However, in scripts it is overkill and your method works faster!
The only faster method is to prepare conditional data beforehand:

msg = the_want_us and "glad to see" or "sorry to hear"

print """Dear ....

We are %(msg)s that ...
""" % vars()

- this doesnt require any special things (even module re). and also, I
found that conditions are rarely so compact to be fit into 20 character at
the end of string. And also it is rarely the case that string is short. So
- anyway some preparation is needed (you need to prepare they_want_us
according to the logic).

Sincerely yours, Roman Suzi
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Sunday, September 09, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "Another case of Cherry Coke down the programming hatch!" _/

More information about the Python-list mailing list