Regular expressions newbie: something for templates

John Machin sjmachin at lexicon.net
Mon Mar 11 02:10:51 EST 2002


Skip Montanaro <skip at pobox.com> wrote in message news:<mailman.1015801819.3967.python-list at python.org>...
> Thomas> "This is the test $var1$ and this is $var2$"
>     Thomas> and turn it into
>     Thomas> "This is the test %(var1)s and this is %(var2)s"
> 
> Give this a try:
> 
>     >>> import re
>     >>> s = "This is the test $var1$ and this is $var2$"
>     >>> re.sub(r"\$([a-zA-Z_0-9]+)\$", r"%(\1)s", s)
>     'This is the test %(var1)s and this is %(var2)s'

The truly paranoid may prefer this:

re.sub(r"\$([a-zA-Z_][a-zA-Z_0-9]*)\$", r"%(\1)s", s)



More information about the Python-list mailing list