[英]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()
函數不是強制性的。 我只想知道是否可以不提供起始索引或范圍作為參數。
使用正則表達式呢?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.