我的程序是检查输入语句是否包含not
后跟bad
,并将其替换为good
。例如,如果句子包含not bad
,而在not
和{good
替换它们,如下面的代码所示:
s = 'The day is not bad'
s = s.replace('not bad', 'good')
print(s)
结果是:
^{pr2}$当在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
整个句子都被good
代替了。
你能不能建议一下,如果我得到了像下面这样的东西应该怎么做:
>>> s = 'The day is not at all bad' #input
>>> print(output)
>>> 'The day is good' # the desired output
输出:
^{pr2}$我在这里使用了
if else
条件正则表达式:regex中的
if else
是如何工作的,这是非常简单的if-else regex语法:这意味着“如果命题A为真,那么匹配模式X;否则,匹配模式Y。”
所以在这个正则表达式中:
它与“bad”匹配如果字符串中有“not”,则条件为“not”必须出现在字符串中。在
如果需要,也可以使用此正则表达式:
在这个组中(2)匹配的是“bad”。在
您的字符串:
有几种方法可以解决这个问题。一种方法是将句子转换成一个单词列表,在列表中找到“not”和“bad”,删除它们以及它们之间的所有元素,然后插入“good”。在
另一种方法是使用regular expressions来查找一个匹配“not”的模式,该模式后跟零个或多个单词,后跟“bad”。
^{pr2}$re.sub
函数查找与给定模式匹配的字符串,并将其替换为您提供的字符串:相关问题 更多 >
编程相关推荐