###################################################################### # Author: Dr. Jan Pearce # username: pearcej # Purpose: To demo some string functions ###################################################################### # Acknowledgements: # remove punctuation function # from http://www.ict.ru.ac.za/Resources/cspw/thinkcspy3/thinkcspy3_latest/strings.html # palindromes from http://www.buzzfeed.com/fjelstud/the-21-best-palindromes ###################################################################### import sys def testit(did_pass): """ Print the result of a test. """ # This function works correctly--it is verbatim from the text linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def remove_punctuation(s): '''returns a string with all punctuation removed from input''' # modified from http://www.ict.ru.ac.za/Resources/cspw/thinkcspy3/thinkcspy3_latest/strings.html punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ " # space added s_sans_punct = "" for letter in s: if letter not in punctuation: s_sans_punct += letter return s_sans_punct def is_palindrome(str): '''takes a string input, converts to lowercase, removes punctuation, and returns true if the string is a palindrome''' lowerinput=str.lower() nopunctinput=remove_punctuation(lowerinput) #print(nopunctinput) # for testing purposes return nopunctinput == nopunctinput[::-1] #Some tests testit(is_palindrome("This is a palendome--NOT!")==False) testit(is_palindrome("Nurses RUN!!!")==True) testit(is_palindrome("Mr. Owl ate my metal worm...")==True) testit(is_palindrome("Ogre, flog a golfer. GO!")==True) testit(is_palindrome("Was it a car or a cat I saw?")==True) testit(is_palindrome('A dog! A panic in a pagoda!')==True) builder=['Mom', 'Dad'] buildit="'{0}, {1}, note: I dissent! A fast never prevents a fatness. I diet on {1}, {0}!!'".format(builder[0],builder[1]) #buildit=raw_input('Enter possible paldindrome for testing:\n') if is_palindrome(buildit): print(buildit+' is a palindrome.') else: print(buildit+' is not a palindrome.')