【发布时间】:2019-02-08 21:01:37
【问题描述】:
我有两个字符串:
a = "The quick brown fox did jump over a log"
b = "The brown rabbit quickly did outjump the fox"
两者都已在每个空格处转换为列表。我想创建一个 for 循环,将列表 A 中的每个单词一个接一个地取出,如果找到,则在字符串 B 中搜索它,然后将该单词添加到新字符串中。一旦找到该单词,它将删除第二个字符串中该单词的整个第一次出现。区分大小写,“the”与“The”不一样。我很困惑如何在字符串中搜索特定单词然后删除它。
首先它会从列表 A 中取出单词“The”并在字符串 B 中搜索它,因为找到的新字符串将包含单词“The”。下一个单词是 quick,字符串 B 有 quick,单词 Quickly 包含 quick,所以 quick 会被添加到新字符串中。
我目前的代码:
a = "The quick brown fox did jump over a log"
b = "The brown rabbit quickly did outjump the fox"
import re
aa = re.sub("[^\w]", " ", a).split()
bb = re.sub("[^\w]", " ", b).split()
for aa[0] in range(b):
如果我将列表 A 中的每个单词都搜索到字符串 B,我会得到“The quick brown fox did jump a”
注意:每个单词都区分大小写,如果操作正确,则不应重复单词。
【问题讨论】:
-
在您的示例中,“快速”中的“快速”如何?
-
“Quickly”里面包含“Quick”这个词
-
你应该在你的例子中改变它。因为你有
Next word is "quick", since quick is found inside of "Quickly", quick would be the next word in string C。 -
我编辑了,现在更好了吗?
标签: python string list for-loop python-3.6