欢迎访问www.cnblogs.com/viphhs
A byte of Python《输入与输出》一节中有一个处理回文的小例子(io_input.py)。作者留了个思考题。
如何将标点去掉、忽略大小写后,再考虑是否回文?
可以学习re模块、学习str的方法来处理。
方法1:使用re正则表达式将特殊字符处理为空字符串。
import re
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input("Enter text: ")
something = re.sub(r'[,. -!?:]', '', something)
something = something.lower()
print (something)
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
方法2:使用循环判断每个字符是否在特殊字符串里面,然后将特殊字符替换为空格。
最后使用join和split将空格替换掉。
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input("Enter text: ")
specialstr = (",",".","-","!","?",":")
prostr = list(something)
for i in range(len(something)):
if something in specialstr:
prostr= " "
#将列表变为字符串
something = "".join(prostr)
#将字符串以空格为分隔符,变为列表,再变为不包含空格的字符串 something = "".join(something.split(" "))
#变为小写字符串 something = something.lower()
#打印字符串,确认是否转换好 print (something)
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
RE模块参考文档:
http://www.cnblogs.com/sevenyuan/archive/2010/12/06/1898075.html |