如何在不使用范围的起始索引作为参数的情况下查找句子中第二次或第三次出现的单词的索引号? (python)

How to find the index number of second or third occurence of a word in a sentence, without using starting index or range as parameter? (python)

我有以下句子 -

Sammy likes to swim in the ocean, likes to spin servers, and likes to smile.

我想找到单词第二次出现的起始索引号likes

但我不想使用起始索引号或范围作为 str.find() 函数的参数。

如果可能的话,我想避免使用正则表达式,因为它对于初学者来说很难理解。

注意:使用str.find() 函数不是强制性的。我只想知道是否可以不给起始索引或范围作为参数。

使用第二个捕获组的regular expressions and start and end

import re
s = 'Sammy likes to swim in the ocean, likes to spin servers, and likes to smile.'
m = re.match(r'.*(likes).*(likes).*', s)
m.start(2)  # start of second capturing group
# 61
m.end(2)  # end of second capturing group
# 66
s[m.start(2), m.end(2)]
# 'likes'

使用正则表达式怎么样?

import re

string = 'Sammy likes to swim in the ocean, likes to spin servers, and likes to smile.'
pattern = 'likes'
likes = [(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]
# [(6, 11), (34, 39), (61, 66)]

喜欢[1][0]有你想要的

普通循环方式:

string = "Sammy likes to swim in the ocean, likes to spin servers, and likes to smile."
word = "likes"
indexes = []
for i in range(len(string)):
    if string[i:i+len(word)] == word:
        indexes.append(i)
print(indexes[1]) # Second location, outputs: 34

列表理解:

[i for i in range(len(string)) if string[i:i+len(word)] == word][1] # Outputs: 34