Search code examples
pythonstringpython-2.7positionletters

Python 2.7, how can I find the position of group of letters in a string?


I need to know how can I find ALL the position of a group of letters in a string. For example, in the string "Canyoucanacanasacannercancanacan" the letters "an" recur 7 times. I want to know the exact position of each one, possibly in a list. How can I do?

Thank you!


Solution

  • Surprisingly I couldn't find a duplicate of this question! You can do this using str.index, while updating the starting position that you're looking from to exclude parts of the string you've already checked.

    s = 'Canyoucanacanasacannercancanacan'
    position_list = []
    i = 0
    while True:
        try:
            position = s.index('an', i)
        except ValueError:
            break
        position_list.append(position)
        i = position + 1
    print(position_list)
    

    As someone suggested, you could also use str.find, like this:

    s = 'Canyoucanacanasacannercancanacan'
    position_list = []
    i = s.find('an')
    while i != -1:
        position_list.append(i)
        i = s.find('an', i+1)
    print(position_list)