← Back to Python, page 2

python-0038 · Easy fresher

How do you check whether a string is a palindrome, ignoring case and punctuation?

Normalise the string by keeping only letters and digits in lowercase, then compare it with its reverse. A two-pointer loop that skips non-alphanumeric characters does the same in O(1) extra space.

Full answer
python
def is_palindrome(s):
    cleaned = [c.casefold() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

def is_palindrome_two_pointers(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].casefold() != s[j].casefold():
            return False
        else:
            i, j = i + 1, j - 1
    return True

for text in ["Never odd or even", "A man, a plan, a canal: Panama!", "Python", ""]:
    print(repr(text), is_palindrome(text), is_palindrome_two_pointers(text))

Output:

text
'Never odd or even' True True
'A man, a plan, a canal: Panama!' True True
'Python' False False
'' True True

Both versions agree on every case. The first builds a cleaned list and compares it with its reverse, which is short and clear but uses extra memory. The second walks inward from both ends, skipping punctuation and spaces, and stops at the first mismatch. An empty string counts as a palindrome, an edge case worth stating. isalnum accepts letters and digits from any script, so the functions also work for non-English text.

python
def is_palindrome(s):
    cleaned = [c.casefold() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

def is_palindrome_two_pointers(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].casefold() != s[j].casefold():
            return False
        else:
            i, j = i + 1, j - 1
    return True

for text in ["Never odd or even", "A man, a plan, a canal: Panama!", "Python", ""]:
    print(repr(text), is_palindrome(text), is_palindrome_two_pointers(text))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Normalise case and drop non-alphanumerics
  • Compare with the reverse
  • Two pointers use constant extra space
  • State edge cases such as empty strings

Common mistakes

  • Forgetting punctuation and spaces
  • Using lower() where casefold is safer

Follow-ups

  • How would you find the longest palindromic substring?
  • What is the time complexity of each version?

Tips

  • Offer both versions