擅长:python、mysql、java
<p>有几种方法可以解决这个问题。一种方法是将句子转换成一个单词列表,在列表中找到“not”和“bad”,删除它们以及它们之间的所有元素,然后插入“good”。在</p>
<pre><code>>>> s = 'the day is not at all bad'
>>> start, stop = 'not', 'bad'
>>> words = s.split()
>>> words
['the', 'day', 'is', 'not', 'at', 'all', 'bad']
>>> words.index(start)
3
>>> words.index(stop)
6
>>> del words[3:7] # add 1 to stop index to delete "bad"
>>> words
['the', 'day', 'is']
>>> words.insert(3, 'good')
>>> words
['the', 'day', 'is', 'good']
>>> output = ' '.join(words)
>>> print(output)
the day is good
</code></pre>
<p>另一种方法是使用<a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">regular expressions</a>来查找一个匹配“not”的模式,该模式后跟零个或多个单词,后跟“bad”。<code>re.sub</code>函数查找与给定模式匹配的字符串,并将其替换为您提供的字符串:</p>
^{pr2}$