Python Program to Check if a String is a Palindrome or Not

Palindromes are words or phrases that read the same way backward as they do forward. Examples include “racecar”, “madam”, and “level”. In this tutorial, we will learn how to write a Python program to check if a given string is a valid palindrome or not.

Algorithm for checking if a string is a palindrome:

  1. Convert the string to lowercase
  2. Remove all spaces and punctuation from the string
  3. Reverse the string
  4. Compare the original string with the reversed string. If they are the same, the string is a palindrome.

Let’s start by writing a function that takes a string as input and returns True if it is a palindrome and False otherwise.

def is_palindrome(s):
    # Convert the string to lowercase
    s = s.lower()
    
    # Remove all spaces and punctuation from the string
    s = ''.join(c for c in s if c.isalnum())
    
    # Reverse the string
    s_reverse = s[::-1]
    
    # Compare the original string with the reversed string
    if s == s_reverse:
        return True
    else:
        return False

Let’s test our function with some examples:

print(is_palindrome("racecar")) # True
print(is_palindrome("A man, a plan, a canal, Panama!")) # True
print(is_palindrome("hello")) # False

As we can see, the function correctly identifies the palindromes and non-palindromes.

Now, let’s look at the code in more detail.

First, we convert the input string to lowercase using the lower() method. This ensures that the function can handle strings with mixed case.

Next, we remove all spaces and punctuation from the string using a list comprehension and the isalnum() method. This removes any characters that are not letters or digits.

We then reverse the string using slicing. The syntax s[::-1] means to slice the entire string s, starting at the end and moving backward by one step.

Finally, we compare the original string with the reversed string using an if statement. If the strings are the same, the function returns True, indicating that the input string is a palindrome. If the strings are different, the function returns False.

This algorithm works for most cases, but there are some edge cases that we need to consider. For example, strings that contain non-Latin characters or non-alphanumeric characters may not be handled correctly by our function. To handle these cases, we can use the unicodedata module to normalize the input string before processing it.

import unicodedata

def is_palindrome(s):
    # Normalize the string using NFKD
    s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode('ascii')
    
    # Convert the string to lowercase
    s = s.lower()
    
    # Remove all spaces and punctuation from the string
    s = ''.join(c for c in s if c.isalnum())
    
    # Reverse the string
    s_reverse = s[::-1]
    
    # Compare the original string with the reversed string
    if s == s_reverse:
        return True
    else:
        return False

In this updated version of the function, we first normalize the input string using the NFKD form, which decomposes the string into its constituent parts. We then remove any non-ASCII characters using the encode() and decode() methods. This ensures that the function can handle input strings with non-Latin characters or non-alphanumeric characters.

Follow us on Twitter: Hacktube5

Follow us on Youtube: Hacktube5

Leave a Reply