Home ยป Check for a palindrome in python

Check for a palindrome in python

Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests

A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, dad, mum and toot.

There are also numeric palindromes, including date/time stamps using short digits 11/11/11 11:11 and long digits 02/02/2020.

 

Table of Contents

Example 1

mystring = input("Please Enter a string to check : ")
lowerstring = mystring.casefold()  
  
# This string is reverse.  
reversedstring = reversed(lowerstring)  
  
if list(lowerstring) == list(reversedstring):  
   print(lowerstring + " is a palindrome")  
else:  
   print(lowerstring + " is not a palindrome")  

Lets try this example out

>>> %Run palindrome1.py
Please Enter a string to check : madam
madam is a palindrome
>>> %Run palindrome1.py
Please Enter a string to check : madma
madma is not a palindrome

Example 2

mystring=input(("Please Enter a string to check :"))

if(mystring==mystring[::-1]):  
      print(mystring + " is a palindrome") 
else:  
      print(mystring + " is not a palindrome")  

Lets see a test run

>>> %Run palindrome2.py
Please Enter a string to check :madam
madam is a palindrome
>>> %Run palindrome2.py
Please Enter a string to check :madma
madma is not a palindrome

Link

This is in our github repository

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More