How to Check Palindrome in Python (Ignore Case and Spaces)

Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

14 lines
Python 3.9+
def is_palindrome(text: str) -> bool:
    cleaned = ''.join(char.lower() for char in text if char.isalnum())
    return cleaned == cleaned[::-1]

if __name__ == "__main__":
    test_cases = [
        "A man, a plan, a canal: Panama",
        "race a car",
        "Was it a car or a cat I saw?",
        "hello",
        "No 'x' in Nixon",
    ]
    for phrase in test_cases:
        print(f"{phrase!r:45} -> {is_palindrome(phrase)}")

Output

stdout
'A man, a plan, a canal: Panama'              -> True
'race a car'                              -> False
'Was it a car or a cat I saw?'              -> True
'hello'                                   -> False
"No 'x' in Nixon"                         -> True

How it works

The function first builds a cleaned string with only alphanumeric characters using a generator expression inside join. Each character is lowercased via .lower(), so case differences are ignored. The slice [::-1] creates a reversed copy of the cleaned string, making the comparison straightforward. This approach handles spaces, punctuation, and Unicode letters consistently with the isalnum() check. The result is a simple, readable one-liner that works on any string without external dependencies.

Common mistakes

  • Forgetting that `isalnum()` excludes underscores, so 'hello_world' would still be a palindrome for that part
  • Omitting `.lower()` and getting case-sensitive false negatives like 'Racecar'
  • Using `reverse()` on the original string directly without cleaning it first

Variations

  1. Use `filter(str.isalnum, text)` with `map(str.lower, ...)` for a more functional style
  2. Write a loop comparing characters from both ends instead of reversing the whole string for memory efficiency

Real-world use cases

  • Validating user-generated phrases in word games or puzzle apps where formatting must not affect the answer.
  • Sanitizing and normalizing text for search or fuzzy matching in content management systems.
  • Building interview-style coding challenges or algorithm teaching examples for string manipulation skills.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.