If a word or sentence reads the same way forward and backward, then it is a palindrome. A small admonition is in place, whitespaces and punctuation marks can be ignored. Also, all the letters should be in one case, lower or upper, your choice. Ideal for Python to show off its prowess with string handling.

# check if a phrase is a palindrome
# tested with Python24      vegaseat     10sep2006

def isPalindrome(phrase):
    take a phrase and convert to all lowercase letters and
    ignore punctuation marks and whitespaces,
    if it matches the reverse spelling then it is a palindrome
    phrase_letters = [c for c in phrase.lower() if c.isalpha()]
    print phrase_letters  # test
    return (phrase_letters == phrase_letters[::-1])

phrase1 = "A man, a plan, a canal, Panama!"  # example with punctuation marks
if isPalindrome(phrase1):
    print '"%s" is a palindrome' % phrase1
    print '"%s" is not a palindrome' % phrase1


phrase2 = "Madam in Eden I'm Adam"
if isPalindrome(phrase2):
    print '"%s" is a palindrome' % phrase2
    print '"%s" is not a palindrome' % phrase2
11 Years
Discussion Span
Last Post by Gribouillis

I have found the above program quite good. but how can we modify the program for palindrome ignoring symbols and spaces using .replace and .lower??


Can anyone provide an explanation for the "[c for c in phrase.lower() if c.isalpha()]"
I understand that .lower() makes them lowercased and .isalpha makes sure they are alphabetical, however, I don't understand the syntax

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.