0

我有以下句子-

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

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

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

如果可能的话,我想避免正则表达式,因为初学者很难理解。

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

4

3 回答 3

3

使用第二个捕获组的正则表达式start和: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'
于 2018-01-03T13:01:10.140 回答
1

使用正则表达式怎么样?

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)]

likes[1][0] 有你想要的

于 2018-01-03T13:04:21.963 回答
1

正常循环方法:

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
于 2018-01-03T13:10:44.187 回答