PythonMastery
Python programs · Strings · beginner

Palindrome string program in Python

Check whether a word or phrase reads the same forwards and backwards. Ignores capital letters, spaces and punctuation, so phrases work too.

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

python
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.

output
Enter a word or phrase: Never odd or even
"Never odd or even" is a palindrome

How it works

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:

python
for word in ["racecar", "Racecar", "never odd or even"]:
    print(word, word == word[::-1])
output
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.

Learn the idea: Working with Strings, Control Flow: Conditionals