Home / Python / Example programs / Strings

Python program: Check for a palindrome

A palindrome reads the same forwards and backwards, ignoring spaces, punctuation and capitals.

The code

def is_palindrome(text):
    letters = "".join(ch.lower() for ch in text if ch.isalnum())
    return letters == letters[::-1]

for t in ["racecar", "Never odd or even", "A man, a plan, a canal: Panama!", "Python"]:
    print(f"{t!r}: {is_palindrome(t)}")

Output

'racecar': True
'Never odd or even': True
'A man, a plan, a canal: Panama!': True
'Python': False

How it works

First keep only the letters and digits in lower case, then compare with the reverse.

Python features used

Learn the ideas behind it in the free lesson Strings.