# File: strmisc.py # Do some miscellaneous things with strings # # 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 + '"' # # next, get the substring to find; quit on EOF try: ctstr = raw_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) 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 + '"' print "Replacing", ctstr, "with XXX in", prstr, "gives", prrepstr