1

I am trying to replace words in my string that contain a certain substring. Here is an example

import regex as re

given_in = 'My cat is not like other cats'
desired_out = 'My foo is not like other foo'

I have tried

print(re.sub('cat', 'foo', given_in))
>>>> 'My foo is not like other foos'

and

print(re.sub('.*cat.*', 'foo', given_in))
>>>> 'foo'

What is the right approach here?

2

1 Answer 1

1

This will work:

import re

given_in = 'My cat is not like other cat'
desired_out = 'My foo is not like other foo'

out = re.subn("\w*(cat)\w*", "foo", given_in)
print(out)

output:

'My foo is not like other foo'
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.