Ho to use a regular expression group reference as hash key

Raymond Hettinger python at rcn.com
Mon Mar 11 23:15:41 EST 2002


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


"Andreas Martin" <a.martin at perfectwww.de> wrote in message
news:f2dbb0ed.0203111447.31eddd81 at posting.google.com...
> Hallo !
>
> I'm a Python newbie and I have the following problem:
>
> A hash person={"entry1":"value1","entry2":"value2"}
>
> and I would like to do a substitution with regular expression (an easy
> example)
> like this:
>
> pat = re.compile(r'(entry1)')
> t = pat.sub(person[\1],"something...entry1...something")
>
> I would like to substitute the "entry1" string by the respective hash
> element with the group reference \1 as hash key, that is to say
> t="something...value1...something".
>
> Similar in Perl:
>
> s/(entry1)/%person($1)/
>
> I hope my problem is understandable.
> Thanks





More information about the Python-list mailing list