0

If you were to have a string of characters/numbers in a sequence - say AACBDEFZZBGFAAFFGGCCEEZZ

How could you iterate over the string, and then have every character between the AA and ZZ appear in a list? The end result in this case being:

[CBDEF], [FFGGCCEE] ?

Thanks

1 Answers1

1

You can use str.index:

def between_markers(s, starting_marker="AA", ending_marker="ZZ"):
    # keep track of where the previous marker was found
    prev_ind = 0
    ret = []
    while True:
        try:
            # find the starting marker
            start = s.index(starting_marker, prev_ind) + len(starting_marker)
            # find the ending marker
            end = s.index(ending_marker, start)
            prev_ind = end + len(ending_marker)
            # slice and append to return list
            ret.append(s[start:end])
        except ValueError:
            # couldn't find one of the two markers so we're done
            break
    return ret

between_markers("AACBDEFZZBGFAAFFGGCCEEZZ") # ['CBDEF', 'FFGGCCEE']
Aplet123
  • 33,825
  • 1
  • 29
  • 55