'How to find index of second occurrence of a phrase in a string in Python 3?

How could I (in Python 3) find the index of the second occurrence of a phrase in a string? My code so far is

    result = string.index("phrase im looking for")
    print (result)

which gives me the index for "Phrase im looking for" in the string "string". However, if "phrase im looking for" appears twice, and I want to find the index of the second occurrence (ignoring the first), how could I go about this?



Solution 1:[1]

You can do as follows to find indices of the some phrase, e.g:

import re

mystring = "some phrase with some other phrase somewhere"

indices = [s.start() for s in re.finditer('phrase', mystring)]

print(indices)
%[5, 28]

So obviously the index of second occurrence of 'phrase' is indices[1].

Solution 2:[2]

it can be like this

def second_index(text: str, symbol: str) -> [int, None]:
"""
    returns the second index of a symbol in a given text
"""
first = text.find(symbol)
result = text.find(symbol,first+1)
if result > 0: return result 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin
Solution 2 Mylinear