Your Ad Here

Detecting Palindromes With Python, Revisited

I know this is first year computer science stuff, but it can be fun to play with.

Suppose you want a simple, general purpose function to find palindromes. Here’s what I came up with; we’ll name it “ispal.py”:

#!/usr/bin/python
import sys
import re
q = sys.argv[1]
q = re.sub(”(\s+|’|\.|\,|\!|\?|\:|\;)”, “”, q).lower()
print q==q[::-1]

Line by line, it’s pretty simple.

The first line lets bash know we’re a Python script.

The next two import sys (so we can get the string argument) and re (so we can do regular expressions).

Fourth line, we capture our argument.

Fifth does a lot of the work. Read this as “q is now going to equal a new string in which we substitute anything matching whitespace (\s+) or various punctuation with an empty string (”"), starting with the original q. Oh, and then we’ll make it all lowercase (lower()).”

The last line prints the result of q==q[::-1]; the right hand side treats q as an array and reverses the whole thing. So, this line prints True or False depending on whether the strings are the same when reversed.

And you would run this (after running chmod +x ispal.py):
$ ./ispal.py 'A man, a plan, a canal: Panama!'
$ True
$ ./ispal.py 'This is not a palindrome.'
$ False
$ ./ispal.py 'Madam, I'm Adam.'
$ True

… and so on.

Improvements? I’m not an expert with regular expressions in Python, so it’s very possible that that line could be done better. Anyone?

3 Responses to “Detecting Palindromes With Python, Revisited”


  1. 1 mrben

    I think there are probably a couple of different ways of doing this - there is probably a lambda-type function that will use string.replace for all the characters in string.punctuation (which is a constant list of all the punctuation), which would remove the need for the regex.

    However, with the regex, you can use the \W shortcut for non-alphanumeric characters. Thus the line becomes:

    q = re.sub(”\W”, “”, q).lower()

  2. 2 Phil Crissman

    Nice; I was assuming there was a better way to do that. Thanks for the tip! Apparently, I need a regex refresher.

  3. 3 iffy

    This is a neat little example. I used this as a basis for another version using only list comprehensions — one of my favorite features of Python.

Comments are currently closed.

Your Ad Here