A palindrome reads the same forwards and backwards, like "level" or "racecar". The check is short: compare the text with its reverse, text[::-1].
The program
text = input("Enter a word or phrase: ") cleaned = "" for ch in text.lower(): if ch.isalnum(): cleaned += ch if cleaned == cleaned[::-1]: print(f'"{text}" is a palindrome') else: print(f'"{text}" is not a palindrome')
Typed in this example: Never odd or even. Press Run to type your own.
Enter a word or phrase: Never odd or even "Never odd or even" is a palindrome
How it works
text.lower()makes every letter small, so "N" and "n" count as the same letter.ch.isalnum()isTruefor letters and digits, andFalsefor spaces and punctuation. Only letters and digits are kept, so "Never odd or even" becomesneveroddoreven.cleaned[::-1]is the cleaned text in reverse order. If both are equal, the text is a palindrome.
Why clean the text first
Without the cleaning step, the comparison is exact. A capital letter or a space at a different position is enough to make it fail:
for word in ["racecar", "Racecar", "never odd or even"]: print(word, word == word[::-1])
racecar True Racecar False never odd or even False
"Racecar" reversed is "racecaR", and the reversed phrase has its spaces in different places. Both are palindromes once you ignore case and spaces, which is what the program above does.
Related programs: Palindrome number.