0

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?

user3662991
  • 1,083
  • 1
  • 11
  • 11

2 Answers2

3

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].

Marcin
  • 215,873
  • 14
  • 235
  • 294
  • awesome that works perfectly! would you mind explaining just how it works? i understand as follows: indices (the variable) is assigned the value .... (what is the s.start etc doing?) and re.finditer('phrase', mystring) is finding the index of all occurences of phrase in mystring yeah? Thanks heaps man :) – user3662991 May 27 '14 at 08:40
0

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 
Mylinear
  • 1
  • 1