Introduction
A palindrome is a word, phrase, or sequence of characters that reads the same forwards and backwards,
ignoring spaces, punctuation, and capitalization. For example, “madam” and “racecar” are palindromes,
while “hello” and “world” are not.
In this program, we will write a Python function that checks whether a given string is a palindrome.
We will compare the original string with its reversed version to determine if they are identical.
Objective
The objective of this program is to demonstrate how to check if a given string is a palindrome using Python.
We will focus on:
- Reading an input string from the user.
- Normalizing the string to ignore spaces, punctuation, and case differences.
- Comparing the string with its reversed version to determine if it is a palindrome.
Python Code
def is_palindrome(s): # Normalize the string: remove non-alphanumeric characters and convert to lowercase s = ''.join(c.lower() for c in s if c.isalnum()) # Check if the string is equal to its reverse return s == s[::-1] # Get user input input_string = input("Enter a string to check if it's a palindrome: ") # Check and display result if is_palindrome(input_string): print(f"'{input_string}' is a palindrome.") else: print(f"'{input_string}' is not a palindrome.")
Program Explanation
Let’s break down the program step by step:
- is_palindrome function:
– This function accepts a strings
as its input.
– It uses a list comprehension to filter out non-alphanumeric characters (e.g., spaces, punctuation) and converts all characters to lowercase for uniformity. This ensures that the check is case-insensitive and ignores irrelevant characters.
– Then, the function compares the strings
with its reverses[::-1]
. The slicing techniques[::-1]
creates a reversed version of the string. If the original string matches the reversed string, it is a palindrome. - User Input:
– The program prompts the user to enter a string. Theinput()
function captures the user’s input. - Palindrome Check:
– The string entered by the user is passed to theis_palindrome()
function. The function returnsTrue
if the string is a palindrome andFalse
otherwise. - Output:
– Based on the result fromis_palindrome()
, the program prints whether the string is a palindrome or not.
How to Run the Program
To run the program, follow these steps:
- Ensure you have Python installed on your computer. You can download it from python.org.
- Save the Python code in a file with a .py extension (e.g.,
palindrome_checker.py
). - Open a terminal or command prompt and navigate to the directory where your Python file is located.
- Run the program by typing
python palindrome_checker.py
in the terminal or command prompt. - The program will prompt you to enter a string. After entering the string, it will display whether it is a palindrome or not.