Palindrome program in python 

1. What is a Palindrome?

A palindrome is a sequence of characters that reads the same forward and backward. It can be a word, a number, or even a phrase.
For example:

  • Numbers: “121”, “12321” are the palindrome numbers.
  • Words: “radar”, “madam” are the palindrome numbers.
  • Phrases (ignoring spaces and punctuation): “A man, a plan, a canal, Panama”
  • Words: “Jobbinge” , “python” are not the palindrome numbers.

In programming, to check for a palindrome, one usually compares the initial string or the sequence with its reverse.

2. How to Test for a Palindrome

Step 1: Input the string

We begin by asking the user to input a string using Python’s input() function. This function allows users to type a string that the program can store and process.

Example:

string = input("Enter a string: ")

If the user types “radar”, the variable string will now hold the value "radar".

Step 2: Reverse the String

To check if the string is a palindrome, we reverse the string and compare it with the original. There are several ways to reverse a string in Python:

a. Using Slicing ([::-1]):

Slicing is a short way to reverse a string. The syntax string[::-1] means:

  • Start at the end of the string (indicated by -1).
  • Move backward to the beginning.
  • Collect all characters in reverse order.

Example:

reversed_string = string[::-1]

For string = "radar", reversed_string will also be "radar".

b. Using a Loop:

If slicing feels too magical, you can use a loop to reverse the string. Here’s how:

reversed_string = ""
for char in string:
    reversed_string = char + reversed_string

This takes each character and prepends it to the result. For “radar”, the process looks like:

  • Start with ""
  • Add 'r': "r"
  • Add 'a': "ar"
  • Add 'd': "dar"
  • Add 'a': "adar"
  • Add 'r': "radar"

c. Using reversed() and join():

The reversed() function returns an iterator that moves backward through the string. To turn it back into a string:

reversed_string = ''.join(reversed(string))

Step 3: Compare Original and Reversed Strings

Now that we have both the original string and its reversed version, we simply compare them using the equality operator (==).

Example:

if string == reversed_string:
    print("It is a palindrome.")
else:
    print("It is not a palindrome.")

For string = "radar", the condition string == reversed_string evaluates to True.

Step 4: Handle Case Sensitivity

Python treats uppercase and lowercase characters as different by default. For example:

  • "Radar" is not equal to "radar".

To make the comparison case-insensitive, convert the string to lowercase using the.lower() method before comparing.

Example:

string = string.lower()

This ensures both "Radar" and "radar" are treated as the same.

Step 5: Ignore Non-Alphanumeric Characters

Sometimes, input strings may contain spaces, punctuation, or special characters. For example:

  • "A man, a plan, a canal, Panama" is a palindrome if we ignore spaces and punctuation.

To clean the string:

  1. Remove all non-alphanumeric characters.
  2. Convert the remaining characters to lowercase.

Using regular expressions (regex) is the easiest way:

import re
cleaned_string = re.sub(r'[^A-Za-z0-9]', '', string).lower()

Here’s what happens:

  • r'[^A-Za-z0-9]': Matches anything not a letter (A-Z or a-z) or digit (0-9).
  • re.sub(): Replaces those matches with an empty string ('').
  • .lower(): Converts the cleaned string to lowercase.

3. Basic Palindrome Program

Here’s a simple program:

# Take input from the user
string = input("Enter a string: ")

# Reverse the string using slicing
reversed_string = string[::-1]

# Check if the original string is equal to the reversed string
if string == reversed_string:
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")

Example Run:

Enter a string: radar
'radar' is a palindrome.

Here’s another example:

string = "Jobbinge"
reversed_string = string[::-1]  # "egnibboJ"

if string == reversed_string:
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")

Output:

'Jobbinge' is not a palindrome.

Reason: The reversed string is “egnibboJ”, which is not the same as “Jobbinge”.

4. Case-Insensitive Palindrome Program

To make it case-insensitive:

# Take input from the user
string = input("Enter a string: ")

# Convert the string to lowercase for case-insensitive comparison
string = string.lower()

# Reverse the string using slicing
reversed_string = string[::-1]

# Check if the original string is equal to the reversed string
if string == reversed_string:
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")

Another example:

string = "Jobbinge".lower()  # Convert to lowercase: "jobbinge"
reversed_string = string[::-1]  # "egnibboj"

if string == reversed_string:
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")

Output:

'Jobbinge' is not a palindrome.

Reason: The reversed string (“egnibboj”) does not match the lowercase version of the original string (“jobbinge”).

5. Palindrome Program Ignoring Non-Alphanumeric Characters

For a more robust approach:

import re

# Take input from the user
string = input("Enter a string: ")

# Remove non-alphanumeric characters and convert to lowercase
cleaned_string = re.sub(r'[^A-Za-z0-9]', '', string).lower()

# Reverse the string
reversed_string = cleaned_string[::-1]

# Check if the cleaned string is equal to the reversed string
if cleaned_string == reversed_string:
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")

Example Run:

Enter a string: A man, a plan, a canal, Panama
'A man, a plan, a canal, Panama' is a palindrome.

Another example:

import re

string = "Jobbinge"
cleaned_string = re.sub(r'[^A-Za-z0-9]', '', string).lower()  # "jobbinge"
reversed_string = cleaned_string[::-1]  # "egnibboj"

if cleaned_string == reversed_string:
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")

Output:

'Jobbinge' is not a palindrome.

Reason: After processing, “jobbinge” and “egnibboj” are still not the same.

Summary of Concepts Used

  1. String Slicing ([::-1]): An easy way to reverse a string in Python.
  2. String Methods:
    • .lower(): Guarantees case-insensitivity.
    • re.sub(): Removes unwanted characters for clean comparison.
  3. Conditionals (if-else): Establish whether the string matches its reverse counterpart.
  4. Regular Expressions (re): Used for input cleaning when ignoring spaces and punctuation.