Replace text with value form dictionary (regexp)
Jean-Pierre Bergamin
james at ractive.ch
Wed Mar 3 09:32:57 EST 2004
Jean-Pierre Bergamin wrote:
> 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'?
I have this solution now:
import re
d = {}
d["x"] = 10
d["y"] = "20"
def repl(matchobj):
return str(d[matchobj.group(2)])
p = re.compile('({ ([^}]*) })', re.VERBOSE)
print p.sub(repl, 'foo {x} bar {y} gugu')
Any better solutions?
Regards
James
More information about the Python-list
mailing list