Editor

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

palindrome_string.py
text = "Madam" # or: text = input("Enter a string: ")
word = text.lower() # so "M" and "m" count as the same letter
length = len(word)
is_palindrome = True
# Compare the first letter with the last, the second with the second last, ...
for i in range(length // 2):
if word[i] != word[length - 1 - i]:
is_palindrome = False
break
if is_palindrome:
print(f'"{text}" is a palindrome')
else:
print(f'"{text}" is not a palindrome')
Output
"Madam" is a palindrome

How it works

  1. text.lower() makes the check ignore case, so "Madam" counts as a palindrome.
  2. The loop compares word[i] with word[length - 1 - i]: the first letter with the last, the second with the second last, and so on.
  3. Only half the string needs checking, which is why the loop runs length // 2 times.
  4. As soon as one pair does not match, is_palindrome becomes False and break ends the loop.

Other ways to write it

Using string slicing

Using string slicing
for text in ["level", "Racecar", "python"]:
word = text.lower()
if word == word[::-1]:
print(text, "is a palindrome")
else:
print(text, "is not a palindrome")
Output
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

Ignoring spaces and punctuation
sentence = "A man, a plan, a canal: Panama"
letters = ""
for ch in sentence:
if ch.isalnum(): # keep only letters and digits
letters += ch.lower()
print("Letters only:", letters)
if letters == letters[::-1]:
print("The sentence is a palindrome")
else:
print("The sentence is not a palindrome")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises