Reputation: 167
Let's say there is a string "abcd#abcd#a#"
How to get the index of the 2nd occurrence of '#' , and get the output as 9? Since the position of the second occurrence of '#' is 9
Upvotes: 1
Views: 1280
Reputation: 42708
Using a generator expression:
text = "abcd#abcd#a#"
gen = (i for i, l in enumerate(text) if l == "#")
next(gen) # skip as many as you need
4
next(gen) # get result
9
As a function:
def index_for_occurrence(text, token, occurrence):
gen = (i for i, l in enumerate(text) if l == token)
for _ in range(occurrence - 1):
next(gen)
return next(gen)
Result:
index_for_occurrence(text, "#", 2)
9
Upvotes: 1