1,105,328 Community Members

Palindrome Checking (Python)

Member Avatar
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
 
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
Member Avatar
Kolz
Newbie Poster
12 posts since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
1
 

Is there a way to change this to a while?

Member Avatar
kisan
Newbie Poster
4 posts since Nov 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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??

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

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

Member Avatar
Baladya4
Newbie Poster
1 post since Oct 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
Gribouillis
Posting Maven
3,452 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 883 [?]
Skill Endorsements: 18 [?]
Moderator
 
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

You
Post:
Start New Discussion
Tags Related to this Article