How to find char in string and get all the indexes?

This is because str.index(ch) will return the index where ch occurs the first time. Try:

def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

This will return a list of all indexes you need.

P.S. Hugh’s answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing [] to ().

Leave a Comment