In this Python Program, we will learn how to check whether a string is a palindrome or not.
A palindrome is a word, number, phrase, or other sequences of characters that reads the same backward as forward, such as civic or rotator or the number 14241.
A string is a palindrome when we reverse the string and after reversing the string, the reversed string is equal to the original string entered by the user.
Here is the code of the program to check whether a string is a palindrome or not.
Python Program to Check Whether a String is a Palindrome or Not using reversed() function
# Python Program to Check Whether a String is Palindrome or Not
# To Take the Input from the User
my_str = input("Enter the String: ")
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Enter the String: Level
The string is a palindrome.
Enter the String: Tutorialsrack
The string is not a palindrome.
Program 1: Python Program to Check Whether a String is Palindrome or Not Without using reversed() function
# Python Program to Check Whether a String is Palindrome or Not
# To Take the Input from the User
my_str = input("Enter the String: ")
# make it suitable for caseless comparison
my_str = my_str.casefold()
reverseval = my_str[::-1]
if my_str == reverseval:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Enter the String: Level
The string is a palindrome.
Enter the String: Tutorialsrack
The string is not a palindrome.
Comments