1

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'.

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way the above regex can be obtained without lambda.
@BHATIRSHAD, With my knowledge, it's not possible unless it simple translation of a to 1, w to 2, k to 2. For such simple case, you don't need to use regular expression. Use string.translate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.