Palindrome

Skip Montanaro skip at pobox.com
Fri Nov 14 04:47:07 CET 2003


    Andrew> Gerrit Holl
    >> Are you looking for:
    >> 20:58:42:232:0  >>> def ispalindrome(s):
    >> 20:58:42:232:0  ...  return s == s[::-1]

    Andrew> No.  The OP wanted to strip special characters and
    Andrew> normalize case, so that
    Andrew>   A man, a plan, a canal -- Panama!
    Andrew> would be allowed as a palindrome.

Oh, then how about:

    import re
    def ispalindrome(s):
        s = re.sub("[^A-Za-z0-9]+", "", s).lower()
        return s == s[::-1]

    for s in (
        "A man, a plan, a canal -- Panama!",
        "1234",
        "123321",
        "Madam, I'm Adam."):
        print s, "->", ispalindrome(s)

Skip





More information about the Python-list mailing list