Ho to use a regular expression group reference as hash key

Andreas Martin a.martin at perfectwww.de
Tue Mar 12 11:37:27 EST 2002


Hi !

I would like to use html templates with my own tags, e.g.
<td><my-own-tag faxnumber</td> and to substitute <my-own-tag
faxnumber> with the entry hash["faxnumber"] that is to say the saved
faxnumber. That's why I would like to substitute the matching
<my-own-tag key> by the hash entry and the key string should be
referenced by \1 .

Something like this:
pat = re.compile(r'\<my-own-tag (.*?)>')
t = pat.sub(hash[\1],TemplateInput)

The programm should only substitute my own tags. If I try to
substitute every word then words I use as hash key would be
substituted too but I don't want this.

Thank you


"Raymond Hettinger" <python at rcn.com> wrote in message news:<a6jve0$t1h$1 at bob.news.rcn.net>...
> Maybe the % substitution operator will help.
> 
> >>> person={"entry1":"value1","entry2":"value2"}
> >>> target = 'A sample sentence with %(entry1)s and %(entry2)s'
> >>> print target % person
> A sample sentence with value1 and value2
> 
> Another method would be to attempt to substitute every word
> and if the word is not is the hash replace it with itself.
> 
> >>> import re
> >>> target = 'A sample sentence with entry1 and entry2'
> >>> person={"entry1":"value1","entry2":"value2"}
> >>> re.sub( r'b\w+\b', lambda word: person.get(word,word), target )
> 'A sample sentence with entry1 and entry2'
> 
> 
> Raymond Hettinger



More information about the Python-list mailing list