Search code examples
pythonstring-function

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.


Solution

  • 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