goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Sunday, March 02, 2008

Python - Palindrome Checker

A palindrome is a sequence that reads the same in either direction.

Here is function I wrote to check if a phrase is a palindrome:


import re

def is_palindrome(txt):
    txt = re.sub('\W+', '', txt).lower()
    return txt == txt[::-1]



phrase = "Go hang a salami, I'm a lasagna hog"
print is_palindrome(phrase)

>> True
#    Comments [4] |
Tuesday, March 04, 2008 4:54:22 AM (Eastern Standard Time, UTC-05:00)
I was always crazy abt python, but never really been able to take off, seeing ur page, i feel like starting all over again.. keep it on corey..u inspire me..
Tuesday, March 04, 2008 8:58:48 AM (Eastern Standard Time, UTC-05:00)
thanks for the kind words. keep reading!

Tuesday, March 04, 2008 4:27:05 PM (Eastern Standard Time, UTC-05:00)
Hi,

I'm new to Python, after years of Perl and other scripting languages. Thanks for your blog, it shows how easy it is to write little but useful programs!
Snark
Sunday, March 16, 2008 8:40:00 PM (Eastern Standard Time, UTC-05:00)
You could also do it this way and you wouldn't even need to import the re module:

txt = filter(lambda c: not c.isspace(), txt).lower()

Comments are closed.