Python Program to Check if a Given String is Palindrome

1. Introduction

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Checking for palindromes is a common problem in programming interviews and competitions.

2. Problem

The problem is to determine if a given string is a palindrome. The solution needs to handle potential edge cases such as capitalization and spaces to ensure accuracy.

3. Solution Steps

1. Normalize the string by converting it to lowercase and removing non-alphanumeric characters.

2. Check if the normalized string is equal to its reverse.

3. Output the result.

4. Code Program

# Define the function to check for a palindrome
def is_palindrome(s):
    # Normalize the string
    normalized_string = ''.join(c for c in s.lower() if c.isalnum())
    # Check if the string is equal to its reverse
    return normalized_string == normalized_string[::-1]

# Given string
input_string = "A man, a plan, a canal: Panama"

# Check if the input_string is a palindrome
palindrome_status = is_palindrome(input_string)

# Print the result
print(f"Is the string a palindrome? {palindrome_status}")


Is the string a palindrome? True


1. The is_palindrome function takes a string s as input.

2. normalized_string is created by filtering s to include only alphanumeric characters, converting it to lowercase for case insensitivity.

3. The == operator checks if normalized_string is the same as its reverse (normalized_string[::-1]).

4. input_string is set to the phrase "A man, a plan, a canal: Panama", which is a well-known palindrome when spacing and punctuation are ignored.

5. palindrome_status receives the boolean result from the is_palindrome function.

6. The final print statement uses an f-string to present the result, indicating the string is a palindrome, denoted by True.