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:
- 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. - 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. - 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