# File: strfind.py # Find a substring in a string # # Matt Bishop, MHI 289I, Winter 2018 # while True: # read in a string; quit on EOF try: instr = raw_input("Enter a string: ") except EOFError: break except: print "Unknown error; EOF to end" continue # # put quotes around the string to show its boundaries when it is printed # prstr = '"' + instr + '"' # read in the string you want to find; quit on EOF try: findstr = raw_input("Enter the string you want to find: ") except EOFError: break except: print "Unknown error; EOF to end" continue # # put quotes around the string to show its boundaries when it is printed # prfindstr = '"' + findstr + '"' # # find the substring # # first, -1 on failure indx = instr.find(findstr) if (indx == -1): print prfindstr, "does not occur in", prstr else: print prfindstr, "first occurs at position", indx, "in", prstr indx = instr.rfind(findstr) if (indx == -1): print prfindstr, "does not occur in", prstr else: print prfindstr, "last occurs at position", indx, "in", prstr # next, exceptions if it doesn't occur try: indx = instr.index(findstr) except ValueError as msg: print prfindstr, "does not occur in", prstr, "--", msg else: print prfindstr, "first occurs at position", indx, "in", prstr try: indx = instr.rindex(findstr) except ValueError as msg: print prfindstr, "does not occur in", prstr, "--", msg else: print prfindstr, "last occurs at position", indx, "in", prstr