# Trace through the code by hand. # Write down all the statements that will be printed on the screen. # # Consider the difference and similarity when using match(), search(), and findall() # find # finditer # findall # search # match # ???? import re def match_occurrence(string, regex): # What does match(string) do? # What does it return? result = [] number_occurrence = 0 print('\n' + "=== match_occurrence ===") match_objects = regex.match(string) if match_objects: print("match_objects = " + match_objects.group()) for occurrence in match_objects.group().split(): number_occurrence = number_occurrence + 1 result.append(occurrence) return result, number_occurrence def search_occurrence(string, regex): # What does search(string) do? # What does it return? result = [] number_occurrence = 0 print('\n' + "=== search_occurrence ===") search_objects = regex.search(string) if search_objects: print("search_objects = " + search_objects.group()) for occurrence in search_objects.group().split(): number_occurrence = number_occurrence + 1 result.append(occurrence) return result, number_occurrence def findall_occurrence(string, regex): # What does findall(string) do? # What does it return? result = [] number_occurrence = 0 print('\n' + "=== find_occurrence ===") find_objects = regex.findall(string) if find_objects: print("find_objects = " + str(find_objects)) for occurrence in find_objects: number_occurrence = number_occurrence + 1 result = find_objects return result, number_occurrence input_string = "A few small syntax errors is OK. But if you are really off we will take off points. " \ "Try to write correct code." regex = re.compile(r'(.f{2})') # what does this regular expression describe? print(match_occurrence(input_string, regex)) print(search_occurrence(input_string, regex)) print(findall_occurrence(input_string, regex)) # note: # find() is a string processing function # findall() is a regular expression function