Check if a String is Palindrome or Not

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, civicradarlevelrotorkayakrevivermadam, 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.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials