Reputation: 8709
I need a regex
that takes the replacement pattern from a dictionary
. I wrote the following code but the pattern gets replaced by the function object
rather than the replacement value.
>>> import re
>>> d1 = {'a':'1'}
>>> d2 = {'w':'2','k':'2'}
>>> re.sub(r'(a)([wk])', '%s%s' %(lambda m:d1[m.group()[0]], lambda m:d2[m.group()[1]]), 'waka')
'w<function <lambda> at 0x7f1e281efc08><function <lambda> at 0x7f1e281efcf8>a'
Expected output is 'w12a'
.
Upvotes: 1
Views: 32
Reputation: 369444
Becasue:
>>> import re
>>> '%s%s' %(lambda m:d1[m.group()[0]], lambda m:d2[m.group()[1]])
'<function <lambda> at 0x0000000002AB0128><function <lambda> at 0x0000000002AB0198>'
You're passing the above string as a replacement string.
Use replacement function as follow:
>>> import re
>>> d1 = {'a':'1'}
>>> d2 = {'w':'2','k':'2'}
>>> re.sub(r'(a)([wk])',
... lambda m: d1[m.group(1)] + d2[m.group(2)],
... 'waka')
'w12a'
Upvotes: 1