emilaz
emilaz

Reputation: 2062

Regex Replace Words Containing Specified Substring

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?

Upvotes: 1

Views: 1270

Answers (1)

Leonardo Scotti
Leonardo Scotti

Reputation: 1080

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'

Upvotes: 1

Related Questions