Python Program to Check a Palindrome String
Beginner · Strings · CBSE class 11 practical list · CBSE class 12 practical list
A palindrome is a word that reads the same forwards and backwards, such as "madam", "level" or "racecar". This program checks a string by comparing its letters from both ends, ignoring the difference between capital and small letters.
Program
"Madam" is a palindrome
How it works
text.lower()makes the check ignore case, so "Madam" counts as a palindrome.- The loop compares
word[i]withword[length - 1 - i]: the first letter with the last, the second with the second last, and so on. - Only half the string needs checking, which is why the loop runs
length // 2times. - As soon as one pair does not match,
is_palindromebecomesFalseandbreakends the loop.
Other ways to write it
Using string slicing
level is a palindrome Racecar is a palindrome python is not a palindrome
word[::-1] is the string reversed, so one comparison does the whole check.
Ignoring spaces and punctuation
Letters only: amanaplanacanalpanama The sentence is a palindrome
isalnum() keeps only letters and digits, so whole sentences with spaces and commas can be checked too.
Try it yourself
Change text to "Noon" and then to "Python", and predict each result before you run it.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises