[Python] How to find all occurrences of a substring?

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    Python has string.find() and string.rfind() to get the index of a substring in a string.

    I'm wondering whether there is something like string.find_all() which can return all found indexes (not only the first from the beginning or the first from the end).

    For example:

    string = "test test test test"

    print string.find('test') # 0
    print string.rfind('test') # 15

    #this is the goal
    print string.find_all('test') # [0,5,10,15]


    For counting the occurrences, see Count number of occurrences of a substring in a string.

    Continue reading...

Compartilhe esta Página