Ho to use a regular expression group reference as hash key

Jason Orendorff jason at jorendorff.com
Tue Mar 12 03:48:33 EST 2002


Raymond Hettinger wrote:
> >>> 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'

The fourth line isn't exactly right.  Should be:

>>> re.sub(r'\b\w+\b', lambda word: person.get(word, word.group(0)), target)
'A sample sentence with entry1 and entry2'

## Jason Orendorff    http://www.jorendorff.com/





More information about the Python-list mailing list