# File: strfind.py # Find a substring in a string # # Matt Bishop, ECS 10, Fall 2012 # # instr = input("Enter a string: ") # put quotes around the string to show its boundaries when it is printed prstr = '"' + instr + '"' # get the substring to find findstr = input("What do you want to find? ") # 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)