0

I'm new to regex and I want to search and replace every occurrence of a "variable".mean() with average("variable")

m863991.mean() to average(m463641) or

m863992.mean() to average(m463642)

Where the beginning of the variable starts with m and ends with 1 or 2 with 5 digits in between.

1 Answer 1

2

You can use re.sub passing lambda for the replacement text. You can use the pattern (.*?)\.mean\(\), and surround the captured group with parenthesis, and starting it with average

>>> import re
>>> text='m863991.mean()'
>>> re.sub('(.*?)\.mean\(\)', lambda  x: 'average('+x.group(1)+')', text)
'average(m863991)'

But to be specific, as you have mentioned the criteria for these values, you can use the pattern (m\d{5}[12])\.mean\(\) for the values that start with m, 5 digits in the middle, and ending with 1 or 2, and .mean() at last.

>>> re.sub('(m\d{5}[12])\.mean\(\)', lambda  x: 'average('+x.group(1)+')', text)
'average(m863991)'
Sign up to request clarification or add additional context in comments.

1 Comment

Worked really well, as expected, exceptional skills, tx

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.