In this Python lesson, we will practice how to write a program that checks if the string is palindrome or not. A string is said to be a palindrome if the characters of the string are read exactly the same forward and backward. Strings whose characters can be read forward and backward are: dad, civic, radar, level, rotor, kayak, reviver, madam, refer etc. Strings whose input are numeric values can also serve as palindrome if the characters can be read forward and backward such as 1234321, 5678765, 923101329 etc.
Example 1: Check Whether a String is a Palindrome or Not
str = input('Enter a string: ')
# make it suitable for caseless comparison
str = str.casefold()
# reverse the string
rev_str = reversed(str)
# check if the string is equal to its reverse
if list(str) == list(rev_str):
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')
Output
Enter a string: madam12321madam
The string is a palindrome.
In the above program, we checked if the string is a palindrome or not. We used the casefold() method to ensure that we make it suitable for caseless comparisons.
Using the reserved() built-in function, we reverse the input string and we used the list() built-in function to convert the string to a list. If the list() function containing the input string is equivalent to the corresponding list() function with the reserved string, the result is a palindrome. Else the result is not a palindrome.