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.
Palindrome Checking (Python)
# 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
kisan 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Baladya4 0 Newbie Poster
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.