擅长:python、mysql、java
<p>您可以使用正则表达式模块,并依赖正则表达式单词边界(<code>\b</code>)来只匹配完整的单词。你知道吗</p>
<p>由于您试图从句子中删除单词,下面的示例将用空字符串替换所有匹配项:</p>
<pre><code>import re
sentence = 'Music world is worldwide'
word = 'world'
removed = re.sub(r'\b%s\b' % word, '', sentence)
print removed # prints "Music is worldwide"
</code></pre>
<p>如果只想找到第一次出现的位置,可以按以下步骤进行:</p>
<pre><code>import re
sentence = 'Music is worldwide in the world'
word = 'world'
match = re.search(r'\b%s\b' % word, sentence)
if match:
print match.start() # prints 26
</code></pre>
<p>有关详细信息,请查看<a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer">^{<cd2>}</a>模块的文档。你知道吗</p>