我的程序是检查输入句子是否包含not
,然后是bad
,并用good
替换它。例如,如果句子包含not bad
没有任何其他字符串中not
和bad
之间,我能够与good
来替换它们,如下面的代码给出:检查句子中是否存在某些字符串并用Python替换为另一个字符串3.6
s = 'The day is not bad'
s = s.replace('not bad', 'good')
print(s)
输出功率为:
>>> The day is good
当not
和bad
之间存在一些其他单词(或单词)时,就会出现问题。 看一看代码我想:
l = ['not', 'bad']
s = 'The day is not so bad'
if l in s:
s = s.replace(l,'good')
它扔像以下的错误而预期输出必须是The day is good
:
Traceback (most recent call last):
File "<ipython-input-69-0eb430659d1e>", line 3, in <module>
if l in s:
TypeError: 'in <string>' requires string as left operand, not list
我想这样的事情太:
list_ = ['not', 'bad']
if any(word in 'The day is not at all bad' for word in list_):
s = s.replace(s,'good')
但我得到的上述代码的错误输出是:
>>> s
>>> good
IOW,整句改为good
。 您能否提供应做什么,如果我要得到的东西像下面这样:
>>> s = 'The day is not at all bad' #input
>>> print(output)
>>> 'The day is good' # the desired output
最后我得到了你想要的东西,我已经更新了我的回答,请检查。 –