简体   繁体   中英

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)

I have the following sentence -

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

I want to find the starting index number of the second occurrence of the word likes

But I don't want to use a starting index number or range as parameter of str.find() function.

If possible I want to avoid regular expression as it is difficult to understand for starters.

NOTE: It is not mandatory to use str.find() function. I just want to know whether it is possible without giving starting index or range as parameter.

Using regular expressions and start and end of the second capturing group:

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'

What about using regex?

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] has what you want

Normal looping method:

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

List comprehension:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM