Check for Palindrome in Python

In the previous article we explored pattern searching in Python, on this article we will see how we can check for Palindrome in Python logic. Before we delve further, think of the date 10-02-2001 which can be expressed as 10022001. From either side, left to right or right to left we arrive at the same number. Such a date is called Palindrome date, suppose we had to implement a program that would validate dates based on the conditions to check if it is a palindrome or not.. what would it’s algorithm and logic look like?

Implementation of Palindrome in Python

We should write the program to accept user given input, check whether the value is palindrome or not and return “YES” or “NO” depending upon it’s validity. If the input is “abba” it should return “YES” as the output. If input is “Python’, it should return “NO”.

The idea is to use two index variables, ‘low’ and ‘high’. The variable ‘low’ is initialized as 0 while ‘high’ is initialized as -1, we then compare the indexes of both variables, because for a string to be a palindrome it requires the first and last character to be the same. Subsequently, if the first and last characters match we then proceed to check the second and second last and so on .. each time the characters on both ends are found to not be matching then the program should terminate the loop and return “NO”.

s=input("Enter a String: ")
high=len(s) -1
while low<high:
    if s[low]!=s[high]:
Enter a String: DAD
Enter a String: CODEKYRO

The loop runs through the characters, and compares them to see where they can be considered symmetric enough to fall under Palindrome classification. It takes care to obtain the right result both on either even or odd case. It stops either when the string is found to not be a palindrome or once it has successfully been considered palindrome.

However, there is a simpler way of checking whether a given string is palindrome.

Alternative method to determine Palindrome in Python

This simple method just checks whether the string in total is equivalent to it’s reversal. The [::-1] expression can be used in Python to reverse the data,  the slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1negative one, which means one step backwards.

s=input("Enter a String:")
if s==s[::-1]:
Enter a String: ABBA

We see that both programs of implementation of Palindrome in Python are able to return the expected statement and validate if it matches the conditions required, in the next article we will explore more on reversal of a string.

Leave a Comment