Palindrome Checking (Python)

vegaseat

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.

950 Views
About the Author

Scientist

# 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
else:
    print '"%s" is not a palindrome' % phrase1

print

phrase2 = "Madam in Eden I'm Adam"
if isPalindrome(phrase2):
    print '"%s" is a palindrome' % phrase2
else:
    print '"%s" is not a palindrome' % phrase2
Kolz 0 Newbie Poster

Is there a way to change this to a while?

kisan 0 Newbie Poster

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??

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

@kisan:
in essence line 10 and 12 contain all of this

Baladya4 0 Newbie Poster

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

Gribouillis 1,391 Programming Explorer Team Colleague

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

Learn about list comprehension syntax in the official documentation http://docs.python.org/tutorial/datastructures.html#list-comprehensions

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.