Trivial string substitution/parser

Samuel newsgroups at debain.org
Sun Jun 17 08:42:41 EDT 2007


On Sun, 17 Jun 2007 11:00:58 +0000, Duncan Booth wrote:

> The elegant and lazy way would be to change your specification so that $
> characters are escaped by $$ not by backslashes. Then you can write:
> 
>>>> from string import Template
>>>> ...

Thanks, however, turns out my specification of the problem was 
incomplete: In addition, the variable names are not known at compilation 
time.
I just did it that way, this looks fairly easy already:

-------------------
    import re

    def variable_sub_cb(match):
        prepend = match.group(1)
        varname = match.group(2)
        value   = get_variable(varname)
        return prepend + value

    string_re = re.compile(r'(^|[^\\])\$([a-z][\w_]+\b)', re.I)

    input  = r'In this string $variable1 is substituted,'
    input += 'while \$variable2 is not.'

    print string_re.sub(variable_sub_cb, input)
-------------------

-Samuel



More information about the Python-list mailing list