Search code examples
pythonpalindrome

How can I remove all spaces and punctuation in determining if a word or phrase is a palindrome? (python)


I want to know if a word or phrase is a palindrome or not.

I get the correct answer when I type "racecar".

But whenever I type something that includes a punctuation like "Was it a cat I saw?", I get the wrong answer.

This is what I have programmed so far.

Please take a look at and tell me what's wrong.

Thanks in advance.

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

Solution

  • This should normalize the string:

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

    gives

    racecar
    

    You can use s.isalnum instead to keep numbers in the string

    And for the test:

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