Palindrome Checking (Python)

vegaseat 0 Tallied Votes 1K Views Share

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

Dani AI

Generated

's original solution is a concise, idiomatic way to filter non-letters and compare the result with its reverse. The thread's follow-ups suggest useful variants: asked for a while-loop approach, about using .replace/.lower, and asked what the comprehension does (as pointed to the docs).

A two‑pointer while-loop avoids allocating a cleaned list or string and answers directly:

def is_palindrome_two_pointer(s):
    i, j = 0, len(s) - 1
    while i < j:
        while i < j and not s[i].isalpha():
            i += 1
        while i < j and not s[j].isalpha():
            j -= 1
        if s[i].casefold() != s[j].casefold():
            return False
        i += 1
        j -= 1
    return True

This is single-pass (O(n)) with O(1) extra memory. casefold() is preferred for Unicode-aware case-insensitive comparison; restrict to ASCII or use .lower() if only ASCII letters are desired.

For a .replace-style cleanup (answering ) the code below produces a cleaned string and compares it to its reverse — simpler to read, slightly more memory use:

import re, string

# regex: keep letters and digits
clean = re.sub(r'[^A-Za-z0-9]', '', s).casefold()
result = (clean == clean[::-1])

# or translate (Python 3): remove punctuation + whitespace
rem = str.maketrans('', '', string.punctuation + string.whitespace)
clean = s.translate(rem).casefold()
result = (clean == clean[::-1])

For : the list-comprehension in the original post is simply shorthand for "loop over each character of the lowercased string, test isalpha(), and collect the passing characters" — it produces the filtered sequence used for the palindrome check. Final notes: include digits with isalnum() if desired, and prefer Python 3 for robust Unicode handling.

Kolz 0 Newbie Poster

Is there a way to change this to a while?

kisan 0 Newbie Poster

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??

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

:
in essence line 10 and 12 contain all of this

Baladya4 0 Newbie Poster

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

Gribouillis 1,391 Programming Explorer Team Colleague

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

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.