Palindrome Checker in Python

A palindrome is a string that reads the same forward and backward. This program checks if a given string is a palindrome.

Python Program


def is_palindrome(s):
    """
    Check if the given string is a palindrome.
    
    Parameters:
    s (str): The string to check.
    
    Returns:
    bool: True if the string is a palindrome, False otherwise.
    """
    # Convert the string to lowercase to make the check case-insensitive
    s = s.lower()
    
    # Remove non-alphanumeric characters
    s = ''.join(char for char in s if char.isalnum())
    
    # Check if the string reads the same forward and backward
    return s == s[::-1]

# Example usage
example_string = "A man, a plan, a canal, Panama"
result = is_palindrome(example_string)
print(f'Is "{example_string}" a palindrome? {result}')

Explanation

This function is_palindrome performs the following steps to check if a string is a palindrome:

  1. Convert to lowercase: The input string is converted to lowercase using the lower() method to make the palindrome check case-insensitive. For example, “A” and “a” are considered the same.
  2. Remove non-alphanumeric characters: The input string is filtered to remove any characters that are not letters or numbers using a generator expression and the isalnum() method.
  3. Check if the string is a palindrome: The filtered string is compared to its reverse using slicing (s[::-1]). If the string is equal to its reverse, it is a palindrome.

Example Usage

The provided example checks if the string "A man, a plan, a canal, Panama" is a palindrome. The output of the program will be:

Is "A man, a plan, a canal, Panama" a palindrome? True

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)