written 2.5 years ago by |
Explanation:-
Method1
A palindrome is a string which is same read forward or backwards. For example: "dad" is the same in forward or reverse direction. Another example is "aibohphobia" which literally means, an irritable fear of palindromes.
In this program, we have taken a string stored in my_str.
Using the method casefold() we make it suitable for caseless comparisons. Basically, this method returns a lowercased version of the string.
We reverse the string using the built-in function reversed(). Since this function returns a reversed object, we use the list() function to convert them into a list before comparing.
Code:-
# Program to check if a string is palindrome or not
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("It is palindrome")
else:
print("It is not palindrome")
Output:-
Method 2
In this program, we have taken a string stored in my_str.
Using the method lower() we make it suitable for caseless comparisons. Basically, this method returns a lowercased version of the string.
the slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1, negative one, which means one step backwards.
Code:-
# Program to check if a string is palindrome or not
my_str = input("Enter the String:- ")
# make it suitable for caseless comparison
my_str = my_str.lower()
# reverse the string
rev_str = my_str[::-1]
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")
Output:-