Python String Pattern Matching Algorithm