用python判断字符串是否是回文结构
上一篇 /
下一篇 2014-06-05 17:30:42
/ 个人分类:Python
第一种:通过字符串前后对比
Str = input("Please input one string:")
newStr = str(Str)
flag = True
for i in range(int(len(newStr)/2)):
if newStr[i]!=newStr[len(newStr)-i-1]:
flag = False
break
if flag:
print("%s is huiwen number!" %Str)
else:
print("%s is not huiwen number!" %Str)
第二种:更为简单,把字符串转为list,然后reverse,把两个字符串对比
import string
import copy
#get the str from command line
Str = input("Please input one str that you want to check:")
punctuation = string.punctuation #string.punctuation里面包含了32个英文标点符号
identify = ' '*32
table = Str.maketrans(punctuation, identify)#maketrans接受两个等长的参数,形成一个对应表
newStr = Str.translate(table).replace(' ', '')#先用对应表和translate函数将字符串里面的标点符号用空格代替,然后去掉空格
inputStr = list(newStr)
temp = copy.deepcopy(inputStr)
inputStr.reverse()
if (temp == inputStr):
print("Yes, it is!")
else:
print("sorry, this str is not!")
收藏
举报
TAG: