How to find the umpteenth occurrence of a substring?

Asked

Viewed 177 times

1

I need to do a function that takes as input a string, a letter, and a number that indicates the desired occurrence of the letter (1 for first occurrence, 2 for second, etc).

The function needs to return where the string position is.

If there are fewer occurrences of the letter than the requested occurrence, the function must return -1.

Example: ("Mariana eats banana",'a',3). Answer: 6 (position of the third occurrence of the letter 'a' in the given string)

Trying:

    def posLetra(string,letra,n):
        i=0
        indice=0
        while i<len(string):
            x=str.find(string,letra)
            indice=indice+x
            i=i+0
        return indice

2 answers

1

You can use the builtin function enumerate() that returns a list tuples containing a count of the iterable passed as parameter where in each tuple the index 0 is the position of the element in the iterable and the index 1 is the element itself.

#t é o texto, l é a letra e n é número da ocorrência a ser pesquisada
def posLetra(t, l, n):
    correncias = []                  #Lista em que serão salvas as posições de cada ocorrencia de l
    for c in enumerate(t):           #Para cada tupa c na enumeração de t...
        if c[1] == l:                ##...se o caractere enumerado for igual a l...
            correncias.append(c[0])  ##...adiciona sua posição na lista de correncias.
    if n >= len(correncias):         #Se a ocorrência a se pesquisada for maior que a quantidade de ocorrência encontradas...
        return -1                    #...retorna -1.
    return correncias[n - 1]         #Retorna a ocorrência n.
    
        

The same code above using comprehensilist on and conditional expression:

def posLetra(t, l, n):
    correncias = [c[0] for c in enumerate(t) if c[1] == l]
    return -1 if n >= len(correncias) else correncias[n - 1]
    
        

1

find returns the position of the first occurrence it finds, but it is possible to pass as parameter the position from which the search is made.

I mean, just call find several times, using the previous position as reference for the next search:

def find_nth(texto, busca, n):
    pos = texto.find(busca)
    while pos >= 0 and n > 1:
        pos = texto.find(busca, pos + 1)
        n -= 1
    return pos
 
print(find_nth('mariana come banana', 'a', 3)) # 6
print(find_nth('mariana', 'a', 10)) # -1

The while continues until the n-th occurrence occurs, or until find return -1 (which indicates that there are no more occurrences).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.