# File: strmisc.py # Do some miscellaneous things with strings # # Matt Bishop, MHI 289I, Fall 2024 # while True: # read in a string; quit on EOF try: instr = 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 + '"' # # next, get the substring to find; quit on EOF try: ctstr = input("What substring should I count? ") except EOFError: break except: print("Unknown error; EOF to end") continue # # put quotes around the string to show its boundaries when it is printed # prctstr = '"' + ctstr + '"' # now print the count count = instr.count(ctstr) if count == 1: times = "time" else: times = "times" print(prstr, "contains the string", prctstr, count, times) # # does it start and/or end with the string? # if instr.startswith(ctstr): print(prstr, "begins with", prctstr) if instr.endswith(ctstr): print(prstr, "ends with", prctstr) # # now do a replacement # repstr = instr.replace(ctstr, "XXX") prrepstr = '"' + repstr + '"' prctstr = '"' + ctstr + '"' print("Replacing", prctstr, "with XXX in", prstr, "gives", prrepstr)