0
"/home/hernan/PycharmProjects/test1/tensor.py".find('e')   #Returns 4
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',2) #Also 4
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',3) #Also 4

I would like something like:

"/home/hernan/PycharmProjects/test1/tensor.py".find('e',2) #Returns 7
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',3) #Returns 14

Those are the second and third ocurrences of 'e'.

Any built-in function in Python 3.x to get the index of the nth ocurrence of a character in a string?

Hernan
  • 1,149
  • 1
  • 11
  • 29
  • Why not use for-loop? – Philip Tzou May 06 '19 at 23:35
  • i Could do that, but Im looking for a built-in function in Python. I've specified my answer so that it is clearer. – Hernan May 06 '19 at 23:38
  • I see. There's a very comprehensive question and answers on Stackoverflow (https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string). However I don't believe there's any built-in function that can achieve this. – Philip Tzou May 06 '19 at 23:42

2 Answers2

1

Why not just use a for-loop?

def find_nth(text, sub, nth):
    start = -1
    for i in range(nth):
        start = text.find(sub, start + 1)
        if start == -1:
            break
    return start


find_nth("/home/hernan/PycharmProjects/test1/tensor.py", 'e', 2) # returns 7
find_nth("/home/hernan/PycharmProjects/test1/tensor.py", 'e', 3) # returns 24
Philip Tzou
  • 5,926
  • 2
  • 18
  • 27
0

The second argument in the str.find function is to indicate the start index. Not the index of the occurrence to start looking from. 'find a char'.find('a', 3) is equivalent to 'find a char'[3:].find('a') + 3 (sort of; not dealing with the search string not being present in the full string that it's being searched for in). You'll have to write your own function for this.

def search(full, toFind, occ):
    ret = 0
    while occ:
        ret = full.find( toFind, ret ) + 1
        occ -= 0
        if ret == -1:
            return -1
    return ret
mypetlion
  • 2,415
  • 5
  • 18
  • 22