Python Program to Check if a String is Palindrome or Not

Recently, I was working on a project where I had to validate user inputs in a form. One of the requirements was to check whether the entered text was a palindrome.

At first, I thought this would be a simple problem, but as I started exploring, I realized there are multiple ways to solve it in Python. Each method has its advantages depending on the scenario.

In this tutorial, I will cover different methods, explain the logic step by step, and also provide complete Python code examples. By the end of this article, you will have a clear understanding of how to check if a string is a palindrome in Python.

What is a Palindrome?

A palindrome is a word, phrase, or sequence that reads the same backward as forward.

Some common examples include:

  • “madam”
  • “racecar”
  • “level”
  • “civic”

In the USA, one popular palindrome phrase is “A man, a plan, a canal, Panama”. If you ignore spaces and case, it reads the same forward and backward.

Method 1 – Use String Slicing

The simplest way to check if a string is a palindrome in Python is by using slicing.

Here’s how I do it:

# Method 1: Using String Slicing

def is_palindrome(text):
    # Convert to lowercase for case-insensitive comparison
    text = text.lower()
    # Remove spaces for phrases
    text = text.replace(" ", "")
    return text == text[::-1]

# Example usage
word = "Racecar"
if is_palindrome(word):
    print(f"'{word}' is a palindrome")
else:
    print(f"'{word}' is not a palindrome")

You can see the output in the screenshot below.

palindrome string program in python using for loop

Explanation:

This method is quick and works well in most cases.

Method 2 – Use a For Loop

Sometimes, I prefer to manually check each character. This approach helps beginners understand the logic without relying on slicing.

# Method 2: Using a For Loop

def is_palindrome(text):
    text = text.lower().replace(" ", "")
    length = len(text)

    for i in range(length // 2):
        if text[i] != text[length - i - 1]:
            return False
    return True

# Example usage
word = "Level"
if is_palindrome(word):
    print(f"'{word}' is a palindrome")
else:
    print(f"'{word}' is not a palindrome")

You can see the output in the screenshot below.

string palindrome in python

Explanation:

  • I compare the first character with the last, the second with the second last, and so on.
  • If any mismatch is found, the function returns False.

This method is slightly longer but gives you more control.

Method 3 – Use the re Module (Handling Punctuation)

In real-world applications, users often enter text with punctuation. For example: “Madam, I’m Adam” is a well-known palindrome phrase.

To handle such cases, I use the re module to remove non-alphanumeric characters.

# Method 3: Using Regular Expressions

import re

def is_palindrome(text):
    # Keep only alphanumeric characters
    text = re.sub(r'[^A-Za-z0-9]', '', text.lower())
    return text == text[::-1]

# Example usage
sentence = "Madam, I'm Adam"
if is_palindrome(sentence):
    print(f"'{sentence}' is a palindrome")
else:
    print(f"'{sentence}' is not a palindrome")

You can see the output in the screenshot below.

palindrome string in python

Explanation:

  • re.sub(r'[^A-Za-z0-9]’, ”, text.lower()) removes everything except letters and numbers.
  • After cleaning, I compare the string with its reverse.

This method is best when dealing with user inputs in web forms or data processing.

Method 4 – Use Recursion

As an experienced Python developer, I often experiment with recursion for problems like this.

# Method 4: Using Recursion

def is_palindrome(text):
    text = text.lower().replace(" ", "")

    # Base case
    if len(text) <= 1:
        return True

    # Recursive case
    if text[0] == text[-1]:
        return is_palindrome(text[1:-1])
    else:
        return False

# Example usage
word = "Civic"
if is_palindrome(word):
    print(f"'{word}' is a palindrome")
else:
    print(f"'{word}' is not a palindrome")

Explanation:

  • If the first and last characters match, I call the function again on the substring.
  • If they don’t match, it’s not a palindrome.

This method is elegant but not as efficient as slicing or loops for very large strings.

Method 5 – Use Python’s reversed() Function

Another approach is to use the built-in reversed() function in Python.

# Method 5: Using reversed() Function

def is_palindrome(text):
    text = text.lower().replace(" ", "")
    return text == ''.join(reversed(text))

# Example usage
word = "Radar"
if is_palindrome(word):
    print(f"'{word}' is a palindrome")
else:
    print(f"'{word}' is not a palindrome")

Explanation:

  • reversed(text) returns an iterator of characters in reverse order.
  • I join them back into a string and compare with the original.

This is another clean and Pythonic solution.

Performance Considerations

  • String slicing is the fastest and most commonly used method.
  • Looping gives more control but is slightly slower.
  • Recursion is elegant, but not suitable for very long strings due to recursion depth limits.
  • Regex cleaning is necessary when handling user inputs that may contain punctuation or special characters.

When working with large text data (for example, analyzing survey responses in the USA education sector), I usually go with string slicing + regex cleaning for both speed and accuracy.

Practical Example – Check Palindromes in a List

In real applications, you may need to check multiple Python strings at once.

# Checking multiple strings

words = ["Madam", "Python", "Racecar", "USA", "Level"]

for w in words:
    if is_palindrome(w):
        print(f"{w} is a palindrome")
    else:
        print(f"{w} is not a palindrome")

This way, you can validate a list of words or even an entire dataset.

While Python does not have a built-in function to check palindromes, we can easily implement our own using different approaches.

I often start with string slicing because it is simple and efficient. For more advanced use cases, I combine slicing with regex cleaning to handle punctuation and spaces.

If you want to practice Python, this is a great beginner-friendly problem that teaches you about strings, loops, recursion, and built-in functions.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.