要想检查文本是否属于回文需要忽略其中的标点、空格与大小写。例如,“Rise to vote, sir.”是一段回文文本,但是我们现有的程序不会这么认为。你可以改进上面的程序以使它能够识别这段回文吗?
import string
def reverse(text):
return text[::-1] #如果给定一个负数步长,如 -1 ,将返回翻转过的文本。
def is_palindrome(text):
return text == reverse(text)
def capital(text):
'''
返回大写字符
'''
return text.upper()
def removePunctuation(text):
'''
去除标点
'''
return ''.join(e for e in text if e.isalnum())
text = 'Rise to vote, sir.'
text = removePunctuation(text) #Risetovotesir
text = capital(text) #RISETOVOTESIR
if is_palindrome(text):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")