要想检查文本是否属于回文需要忽略其中的标点、空格与大小写。例如,“Rise to vote, sir.”。

#coding=utf-8 import string

Function: to check whether the string is palindrome or not.
Ignore space(空格), case(大小写) and punctuation(标点符号).

def reverse(text): return text[::-1]

def is_palindrome(text): text = text.lower(); text = text.replace(' ', '') punctuation = (',','.',':','。','?') for char in punctuation: text = text.replace(char,'') return text == reverse(text)

something = raw_input("Enter text:") if is_palindrome(something): print("Yes,{} is a plaindrome.".format(something)) else: print("No, {} is not a plaindrome.".format(something))

使用PyCharm的执行结果: 不是回文的输入: C:\Python27\python.exe D:/PycharmProjects/untitled1/io/io_ignoreinput.py Enter text:Rise to vote+,,# No, Rise to vote+,,# is not a plaindrome.

Process finished with exit code 0

是回文的输入: C:\Python27\python.exe D:/PycharmProjects/untitled1/io/io_ignoreinput.py Enter text:Rise to vote,sir. Yes,Rise to vote,sir. is a plaindrome.

Process finished with exit code 0

说明:本例子输入的不是回文的文本(即正反读取都一样),可输入madam,ofo这样的例子