Python program to find Palindrome

 

This python example script will help you to find out the entered string is a palindrome or not. The logic is reversing the original string and comparing both the original and reversed string.

Here is the script (palidrome.py):

The code is self explanatory, read the comments in the script.

print("Enter a word")
#get the string
mystring = str(input())
#remove space
mystring = mystring.replace(" ", "")
#remove special characters
mystring = ''.join(e for e in mystring if e.isalnum())
#change all characters to lower case
mystring = mystring.lower()
#reverse the string
revstring = mystring[::-1]
if(mystring == revstring):
    print("Palindrome")
else:
    print("Not Palindrome")

Steps are:

1. Read the string using python function raw_input() and store it in a variable mystring 
2. Remove space from using replace() function
3. Remove special characters from the string using isalnum() – this function allows only alphabets
4. Change all characters to lower case
5. Now reverse the string using [::-1] and store it in another variable revstring
6. Finally compare both mystring and revstring by == double equal operator

If both the string matches print “Palindrome” or else print “Not Palindrome”


Some palindrome words and sentences to check this script:

1. madam
2. civic
3. A man, a plan, a canal: Panama.
4. No lemon, no melon.

If you are a Python Web developer you may need this CGI script to run on your server:

#!/usr/bin/python
print "Content-type: text/html\n\n";

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

mystring = form.getvalue('string')

if(mystring):
	#remove space
	mystring = mystring.replace(" ", "")
	#remove special characters
	mystring = ''.join(e for e in mystring if e.isalnum())
	#change all characters to lower case
	mystring = mystring.lower()
	#reverse the string
	revstring = mystring[::-1]
	if(mystring == revstring):
		print("Palindrome")
	else:
		print("Not Palindrome")

print '''
<html>
<body>
    <h3>Web Based Python script to Find a string is Palindrome or Not</h3>
    <form action="" method="post">
        <label>Enter a word or a sentence<label>
        <input type="text" name="string" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>
 
'''

You can also see the Python web script demo here:

demo

Same program is written in PHP and Java, If you want please have a look:

PHP: http://www.tutorialsmade.com/php-program-find-palindrome/

JAVA: http://www.tutorialsmade.com/java-program-string-palindrome/

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top