Python programs · Strings
Python program to check a palindrome string
A palindrome reads the same forwards and backwards, like madam or level.
Approach
- Read the text.
- Reverse it with
[::-1]. - Compare the original with the reversed text.
The program
text = input() if text == text[::-1]: print(text, "is a palindrome") else: print(text, "is not a palindrome")
Sample run
Input
madam
Output
madam is a palindrome
How the code works
Reversing with [::-1] and comparing with == is all that is needed. For phrases, first remove the spaces and change everything to lower case, for example cleaned = text.replace(" ", "").lower(), because capital letters and spaces would otherwise make the two sides differ.
Try changing it
- Ignore spaces and capital letters so that phrases such as "Never odd or even" count.
- Check numbers by converting them with
str().
Common mistakes
- Comparing
textwithtext.reverse(), which does not exist for strings. - Forgetting that "Madam" with a capital M is not equal to "madam".