Write a Python palindrome check that ignores case and non-alphanumeric characters.
A palindrome reads the same forwards and backwards, once you have decided what counts as a character. The usual definition for a phrase ignores case, spaces, and punctuation.
def is_palindrome(text):
"""Return True when the text reads the same in both directions."""
cleaned = []
for char in text:
if char.isalnum():
cleaned.append(char.lower())
return cleaned == cleaned[::-1]
print(is_palindrome('A man, a plan, a canal: Panama')) # True
print(is_palindrome('hello')) # False
print(is_palindrome('No lemon, no melon')) # True
The function does three things. It keeps only the letters and the digits, it lowercases them so that the comparison ignores case, and it compares the cleaned list with its own reverse.
Two details are worth explaining. The isalnum() test is what removes the punctuation and the spaces, and it understands Unicode, so accented letters are kept rather than thrown away. The comparison also uses a list rather than the original string, because once the punctuation is gone it is the sequence of characters that matters and not the spacing between them.
There is a faster variant that avoids building the reversed copy. It walks two pointers from each end of the cleaned list towards the middle and compares the characters as it goes. It does the same amount of work, but it uses a constant amount of extra space, and that only matters when the input is very large.
The one-line version that people sometimes give, which compares the text with text[::-1], is only correct when you do not need to ignore anything. It also fails on the empty string in some careless implementations, because the empty string is trivially a palindrome and the check has to handle that case on purpose rather than by accident.