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.
Python code
14 linesdef 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
'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
- Use `filter(str.isalnum, text)` with `map(str.lower, ...)` for a more functional style
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.