2016-05-15 11 views
1

我想知道一個單詞或短語是否是迴文。如何在確定單詞或短語是否爲迴文時刪除所有空格和標點符號? (python)

當我輸入「racecar」時,我會得到正確的答案。

但是,只要我輸入包含像「我是否看到貓?」這樣的標點符號的東西,我就會得到錯誤的答案。

這是我迄今編程的東西。

請看看並告訴我什麼是錯的。

在此先感謝。

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.") 
+0

您需要調試您的程序。嘗試在'if a == a'之前添加'print(e,a)'來查看您實際比較的結果 – Alik

+0

您正在檢查句子末尾是否有問號?你有沒有在輸入中加入? –

+0

是的,我在輸入中包含了問號 – kim

回答

1

這應該正常化的字符串:

s="race. car, " 
"".join(x for x in s if x.isalpha()) 
print s 

racecar 

您可以使用s.isalnum,而不是保持數字的字符串

,並在測試:

if e == e[::-1]: print "palindrome" 
+0

我改變了我的代碼爲e =「」。join(c for c in a1 if c.isalpha())但它仍然無法正常工作。這有什麼問題? – kim

+0

您正在比較('e == a')該字符串與原始輸入,而不是您想要將其與其相反('e == e [:: - 1]')進行比較 – perreal

0

一個字符串的逆轉,您可以使用反向方法

c= a.reverse() 
c.replace (' ','') 
a.replace(' ','') 
If a == c : 
    Print ("pallindrome ") 
Else : 
    Print("not a pallindrome !!) 
+1

你確定Python中的字符串有'reverse'方法嗎?我無法在[docs]中找到它(https://docs.python.org/3.5/library/string.html) – Alik

+0

它們不會在當前版本的Python 2或Python 3中都找不到。在我的答案中使用了'reverse'函數,它使用包含'str'的​​任何序列。 – amiller27

+0

'list'有這個方法。 'str'不。 – TheRandomGuy

0

你想要什麼,其實很簡單的Python:

a = [c for c in input() if c.isalpha()] 
if list(reversed(a)) == a: 
    print('palindrome') 
else: 
    print('not palindrome') 
0

一個選項是使用str.translate並將想要刪除的字符作爲參數傳遞:

import string 

s = 'Was it a cat I saw?' 
s = s.translate(None, string.punctuation + ' ').lower() 
print(s) # wasitacatisaw 
相關問題