Regular expressions newbie: something for templates

Skip Montanaro skip at pobox.com
Sun Mar 10 18:11:03 EST 2002


    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'

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
"As often happens in Net communities, people find all kinds of energy to
compose incisive criticisms of the threads and postings of other members,
when they could be directing that energy towards brilliant new threads and
postings of their own." - Tom Neff




More information about the Python-list mailing list