Regular expressions newbie: something for templates

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Mar 11 03:56:35 EST 2002


"Thomas Weholt" <thomas at weholt.org> wrote in
news:idRi8.7723$eJ6.142517 at news2.ulv.nextra.no: 
> I'm not getting the hang of regular expressions. All I want to do is
> this. 
> 
> Take string #1 :
> 
> "This is the test $var1$ and this is $var2$"
> 
> and turn it into
> 
> "This is the test %(var1)s and this is %(var2)s"
> 

When in doubt, avoid regular expressions. You might be better off doing 
something like this, which also allows you to escape a dollar sign into 
your output string:

>>> s = "This is the test $var1$ and this is $var2$"
>>> def template(s):
...     lst = s.split('$')
...     for i in range(1, len(lst), 2):
...         if lst[i]:
...             lst[i] = '%('+lst[i]+')s'
...         else:
...             lst[i] = '$'
...     return ''.join(lst)
...
>>> print template(s)
This is the test %(var1)s and this is %(var2)s
>>> print template('and this has $$ signs')
and this has $ signs

Optional enhancements would be to check the list length is odd (otherwise 
there was an unmatched dollar) and to replace all % with %% before 
starting.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list