簡體   English   中英

如何在不使用起始索引或范圍作為參數的情況下找到單詞中第二次或第三次出現的索引號? (蟒蛇)

[英]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()函數不是強制性的。 我只想知道是否可以不提供起始索引或范圍作為參數。

使用正則表達式以及第二個捕獲組的startend

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM