1

我正在尝试替换字符串中包含某个子字符串的单词。这是一个例子

import regex as re

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

我努力了

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

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

这里的正确方法是什么?

4

1 回答 1

1

这将起作用:

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)

输出:

'My foo is not like other foo'
于 2021-02-24T13:03:01.630 回答