0

Consider I Want to find 2nd occurence of char 'o' in string 'Hello World'(we can see the index would be 7). Can we write using 'index' or 'find' method in python?

2 Answers2

0

you can do it on several ways, here are some of them:

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

string =  'Hello World'
print (list(find_all(string, 'o'))[1])

output:

7

string =  'Hello World'
print([i for i in range(len(string)) if string.startswith('o', i)][1])

output:

7

ncica
  • 7,015
  • 1
  • 15
  • 37
0

You can use regex, which also works for substrings, as seen in this question:

import re
indexes = [m.start() for m in re.finditer('o', 'Hello World')]  # [4, 7]
print(indexes[1])  # get second occurrence
palvarez
  • 1,508
  • 2
  • 8
  • 18