5

I have a regex <type '_sre.SRE_Pattern'> and I would like to substitute the matched string with another string. Here is what I have:

compiled = re.compile(r'some regex expression')
s = 'some regex expression plus some other stuff'
compiled.sub('substitute', s)
print(s)

and s should be

'substitute plus some other stuff'

However, my code is not working and the string is not changing.

1 Answer 1

7

re.sub is not an inplace operation. From the docs:

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.

Ergo, you must assign the return value back to a.

...
s = compiled.sub('substitute', s)
print(s)

This gives

'substitute plus some other stuff'

As you'd expect.

Sign up to request clarification or add additional context in comments.

Comments

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.