text = raw_input('enter text: ') state = 1 for c in text: if state == 1: if c == 'a': state = 2 elif state == 2: if c == 'b': state = 3 break # accept else: state = 1 if state == 3: print 'match'