Python Program to Check Whether a String is a Palindrome or Not

In this example, we will write a program to take a string input from the user and check if the given string is palindrome or not. To better understand this example, make sure you have knowledge of the following tutorials:-

A string is said to be a palindrome if the reverse of the string is same as string. For example, “madam” is a palindrome, but “program” is noa t palindrome.

Python Program to Check Whether a String is a Palindrome or Not using reversed() method

input_str = input("Enter a string: ")

final_str = ""
rev = reversed(input_str)

if list(input_str) == list(rev):
    print(input_str, "is palindrome")
else:
    print(input_str, "is not palindrome")

The output of the above program is:-

Loading...
Enter a string: madam
madam is palindrome
Program Explanation:
The reversed() method reverses the given string and returns the reversed object which can be used as a list of items. The input string is also converted to a list and compared using a comparison operator.

Python Program to Check Whether a String is a Palindrome or Not using slice operator

string = input("Enter string:")
if string == string[::-1]:
    print(string, "is a palindrome")
else:
    print(string, "is not a palindrome")

The output of the above program is:-

Enter a string: madam
madam is palindrome

Python Program to Check Whether a String is a Palindrome or Not using for loop

str = input("Enter string: ")
is_palindrome = True

for i in range(0, int(len(str)/2)):
        if str[i] != str[len(str)-i-1]:
            is_palindrome = False

if is_palindrome:
    print(str, "is a palindrome")
else:
    print(str, "is not a palindrome")

The output of the above program is:-

Enter a string: madam
madam is palindrome
Loading...
SHARE Python Program to Check Whether a String is a Palindrome or Not

You may also like...

Leave a Reply

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

Share