Swaroop Joshi
Swaroop Joshi

Reputation: 167

Get the nth occurrence of a letter in a string (python)

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

Answers (2)

Netwave
Netwave

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

Jrh
Jrh

Reputation: 57

s = 'abcd#abcd#a#'
s.index('#', s.index('#')+1)

Upvotes: 0

Related Questions