1.11M Members

Palindrome Checking (Python)

 
0
 

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

Is there a way to change this to a while?

 
0
 

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

 
0
 

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

 
0
 

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

 
0
 

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

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This is an OP Kudos discussion and contributors may be rewarded
Post:
Start New Discussion
Tags Related to this Article