python string get index of all occurance code example

Example 1: get all occurrence indices in list python

a_list = [1, 2, 3, 1]

indices = []
for i in range(len(a_list)):
   if a_list[i] == 1:
      indices.append(i)

# more concise way
a_list = [1, 2, 3, 1]
indices = [index for index, element in enumerate(a_list) if element == 1]

Example 2: python find all elements of substring in string

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]