Progress

Python Program to check a string is Palindrome or not

Python Program to check a string is Palindrome or not

Problem Statement: Write a Python program to check if a string is a Palindrome or not.

Description: Palindrome strings are those strings which read same from backwards as forwards like radar, level.

Example:

Input: radar
Outpur: It is Palindrome.
Explanation: The reverse of radar is radar.

Input: coder
Outpur: It is NOT Palindrome.
Explanation: The reverse of coder is redco.

Hint: It is very easy to find reverse of a string in Python using the extended slice syntax which is theString[::-1]. You have the logic, you can write a Python program to check a string a palindrome or not.

Submit your own solution in the comments.

Python Program: Check if String is Palindrome

palindrome.py
Copy
userInput = input("Enter the string: ")

reverse = userInput[::-1] #Reverse a string in Python

if(userInput==reverse):
    print("{} is Palindrome".format(userInput))
else:
    print("{} is not Palindrome".format(userInput))
Output
Enter the string: radar
radar is Palindrome

The logic of the program is in this code userInput[::-1].

It is way to slice a string in Python. In this case, it means to reverse the string (write string from backwards).

And finally, we check if the reverse string is same as the original string to verify if it is Palindrome or not.

One-Line Python Program

Copy
userInput = input("Enter the string: ")

print("It is palindrome" if(userInput==userInput[::-1]) else "It is Not Palindrome")
Output
Enter the string: coder
It is Not Palindrome

The Logic is similar to as the previous program.

It is possible to write the if-else statement in one line and it is very useful to write short and concise code.

Related Python Examples:

Share the Post ;)

Related Posts