Replace text with value form dictionary (regexp)

Scott David Daniels Scott.Daniels at Acm.Org
Wed Mar 3 16:46:40 CET 2004


Jean-Pierre Bergamin wrote:
>I want to implement a small templating system where values in angle
>brackets ...

If you can drop the angle brackets (which in this example even seem to
be braces) and switch to a single delimiter (such as '"' or '|'), you
could use some old magic that now works in 2.3 for normal vectors:
stride expressions.

> I have this solution now:
>     ... d = {}
>     d["x"] = 10
>     d["y"] = "20"
> 
     def repl(template, replace):
         parts = template.split('"')
         if len(parts) & 1 == 0:   # Expect odd rails if even posts
              raise ValueError('Need an even number of quotes, not %d.'
                                % template.count('"')) 

         parts[1::2] = [str(replace[word] for word in parts[1::2]]
         return ''.join(parts)

     repl('"x"+"y" is x+y.', d)

A string like 'This is x: "x' will accidentally replace the final x,
unless you leave the exception test in the code.  If you add an
entry to your dictionary like: d[''] = '"', you can use doubled
quotes to indicate single quotes in the output.

     d[''] = '"'
     repl('"x"+"y" is ""x+y"".', d)

-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list