在确定单词或短语是否为回文时,如何删除所有空格和标点符号? (python)
How can I remove all spaces and punctuation in determining if a word or phrase is a palindrome? (python)
我想知道一个单词或短语是否是回文。
我输入 "racecar" 时得到正确答案。
但是每当我输入包含标点符号的内容时,如 "Was it a cat I saw?",我都会得到错误的答案。
这是我目前编写的程序。
请看一下,有什么问题请指教。
提前致谢。
a1=input("Enter a word or phrase: ")
a=a1.lower()
b=len(a)
c=[]
for i in range(1,b+1):
d=b-i
c.append(a[d])
e="".join(c for c in a1 if c not in ("!",".",":","?"," "))
if e==a:
print (a1,"is a palindrome.")
else:
print (a1,"is not a palindrome.")
要反转字符串,您可以使用 reverse 方法
c= a.reverse()
c.replace (' ','')
a.replace(' ','')
If a == c :
Print ("pallindrome ")
Else :
Print("not a pallindrome !! )
这应该规范化字符串:
s="race. car, "
"".join(x for x in s if x.isalpha())
print s
给
racecar
您可以使用 s.isalnum
来保留字符串中的数字
测试:
if e == e[::-1]: print "palindrome"
你要的其实很简单Python:
a = [c for c in input() if c.isalpha()]
if list(reversed(a)) == a:
print('palindrome')
else:
print('not palindrome')
一种选择是使用 str.translate
并将要删除的字符作为参数传递:
import string
s = 'Was it a cat I saw?'
s = s.translate(None, string.punctuation + ' ').lower()
print(s) # wasitacatisaw
我想知道一个单词或短语是否是回文。
我输入 "racecar" 时得到正确答案。
但是每当我输入包含标点符号的内容时,如 "Was it a cat I saw?",我都会得到错误的答案。
这是我目前编写的程序。
请看一下,有什么问题请指教。
提前致谢。
a1=input("Enter a word or phrase: ")
a=a1.lower()
b=len(a)
c=[]
for i in range(1,b+1):
d=b-i
c.append(a[d])
e="".join(c for c in a1 if c not in ("!",".",":","?"," "))
if e==a:
print (a1,"is a palindrome.")
else:
print (a1,"is not a palindrome.")
要反转字符串,您可以使用 reverse 方法
c= a.reverse()
c.replace (' ','')
a.replace(' ','')
If a == c :
Print ("pallindrome ")
Else :
Print("not a pallindrome !! )
这应该规范化字符串:
s="race. car, "
"".join(x for x in s if x.isalpha())
print s
给
racecar
您可以使用 s.isalnum
来保留字符串中的数字
测试:
if e == e[::-1]: print "palindrome"
你要的其实很简单Python:
a = [c for c in input() if c.isalpha()]
if list(reversed(a)) == a:
print('palindrome')
else:
print('not palindrome')
一种选择是使用 str.translate
并将要删除的字符作为参数传递:
import string
s = 'Was it a cat I saw?'
s = s.translate(None, string.punctuation + ' ').lower()
print(s) # wasitacatisaw