Write Python. Understand every error.

Open the editor

Python programs · Strings

Python program to check a palindrome string

A palindrome reads the same forwards and backwards, like madam or level.

Approach

  1. Read the text.
  2. Reverse it with [::-1].
  3. 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

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: