Replace text with value form dictionary (regexp)

Jean-Pierre Bergamin james at ractive.ch
Wed Mar 3 09:09:19 EST 2004


Hi there

I want to implement a small templating system where values in angle brackets
should be replaced by the corresponding dicitionary value ("foo {x} bar" ->
"foo 10 bar");

>>> d = {}
>>> d["x"] = 10
>>> p = re.compile('{ ( [^}]* ) }', re.VERBOSE)
>>> p.sub(r'd["\1"]','foo {x} bar')
'foo d["x"] bar'

How can I now put the actual value of d["x"] into the string 'foo d["x"]
bar'?


Thanks for your help.


Regards

James





More information about the Python-list mailing list