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.
# Program to check if a string # is palindrome or not # take input from the user my_str = input("Enter a 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")
Enter a string: aIbohPhoBiA It is palindrome
Enter a string: palindrome It is not palindrome
In this program, we have take a string from the user. 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.