A byte of Python in the "Input and Output" section has a small example (io_input.py) dealing with palindrome. The author left a study questions.
How to remove punctuation, ignore the case, and then consider whether palindrome?
You can learn the RE module and learn how to deal with Str.
Method 1: Use the RE regular expression to treat special characters as empty strings.
ImportRedefreverse (text):returnText[::-1]defis_palindrome (text):returnText = =reverse (text) something= Input ("Enter Text:") Something= Re.sub (r'[,. -!?:]',"', something) something=Something.lower ()Print(something)ifIs_palindrome (something):Print("Yes, it is a palindrome")Else: Print("No, it is not a palindrome")
Method 2: Use a loop to determine whether each character is inside a special string, and then replace the special character with a space.
Finally, use join and split to replace the space.
defreverse (text):returnText[::-1]defis_palindrome (text):returnText = =reverse (text) something= Input ("Enter Text:") Specialstr= (",",".","-","!","?",":") Prostr=list (something) forIinchRange (len (something)):ifSomething[i]inchSpecialstr:prostr[i]=" "
#将列表变为字符串something="". Join (PROSTR)
#将字符串以空格为分隔符, becomes a list, and then becomes a string that does not contain spaces
something="". Join (Something.split (" "))
#变为小写字符串
= Something.lower ()
#打印字符串, verify that the conversion is good
Print (something) if Is_palindrome (something): Print ("Yes, it is a palindrome") Else : Print ("No, it is not a palindrome")
Re Module reference Documentation:
Http://www.cnblogs.com/sevenyuan/archive/2010/12/06/1898075.html
[It learning] How Python handles exception special characters