您可以从这里开始简单的字符串操作。 str.index 是你最好的朋友,因为它会告诉你子字符串在字符串中的位置;您也可以稍后在字符串中的某个位置开始搜索:
>>> myString = "this is the initial string"
>>> myString.index('the')
8
>>> myString.index('string', 8)
20
查看切片[8:20],我们已经接近我们想要的:
>>> myString[8:20]
'the initial '
当然,既然我们找到了'the'的起始位置,我们需要考虑它的长度。最后,我们可能想要去掉空格:
>>> myString[8 + 3:20]
' initial '
>>> myString[8 + 3:20].strip()
'initial'
结合起来,你会这样做:
startIndex = myString.index('the')
substring = myString[startIndex + 3 : myString.index('string', startIndex)].strip()
如果您想多次查找匹配项,那么您只需要重复执行此操作,同时仅查看字符串的其余部分。由于str.index 只会找到第一个匹配项,因此您可以使用它来非常有效地扫描字符串:
searchString = 'this is the initial string but I added the relevant string pair a few more times into the search string.'
startWord = 'the'
endWord = 'string'
results = []
index = 0
while True:
try:
startIndex = searchString.index(startWord, index)
endIndex = searchString.index(endWord, startIndex)
results.append(searchString[startIndex + len(startWord):endIndex].strip())
# move the index to the end
index = endIndex + len(endWord)
except ValueError:
# str.index raises a ValueError if there is no match; in that
# case we know that we’re done looking at the string, so we can
# break out of the loop
break
print(results)
# ['initial', 'relevant', 'search']