Skip to content

How to Write a Palindrome Checker in Python: A Step-by-Step Guide

Updated: at 04:12 AM

A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. Some examples of palindromes include “racecar,” “rotator,” and “nurses run.” Palindromes can make for fun recreational puzzles or programming challenges.

In Python, you can write a function to check if a given string is a palindrome. This how-to guide will walk through the key concepts and steps for writing a palindrome checker program in Python.

Table of Contents

Open Table of Contents

Overview

What is a Palindrome?

A palindrome is a string that reads the same forward and backward. Some key properties of palindromes:

Some examples of palindromes:

Palindromes make for interesting recreational puzzles and programming challenges. In Python, we can write a function that takes a string as input and checks if it is a palindrome.

Basic Approach

To check for a palindrome, we can:

  1. Convert the string to lowercase to ignore case.
  2. Remove any non-alphanumeric characters (punctuation, spaces etc).
  3. Compare the string with the reversed string.
  4. If original string is equal to reversed string, then it is a palindrome.

The general logic in pseudocode:

Function is_palindrome(string):

  1. Convert string to lowercase
  2. Remove non-alphanumeric characters
  3. Reverse the cleaned string
  4. If original string is equal to reversed string
     Return True
  Else
     Return False

Next, let’s translate this logic into actual Python code.

Palindrome Checker in Python

Here is an implementation of a palindrome checker function in Python:

import re

def is_palindrome(string):

    # Convert string to lowercase and remove non-alphanumeric characters
    string = re.sub(r'\W+', '', string.lower())

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

    # Compare original and reversed string
    if string == reversed_string:
        return True
    else:
        return False

Let’s break down what this code is doing:

  1. First we import the re module to use regular expressions.

  2. Define a function named is_palindrome() that accepts a string.

  3. Use the regex \W+ to remove any non-alphanumeric characters from the string.

    \W matches any non-alphanumeric character.

    • matches one or more occurrences of the pattern.

    re.sub() replaces these characters with an empty string to remove them.

  4. Convert the cleaned string to lowercase using string.lower().

  5. Reverse the string using string slicing string[::-1]. This is a handy trick in Python.

  6. Compare the original and reversed string using the equality operator ==.

  7. Based on the comparison, return True if it is a palindrome, False if not.

Let’s test it out on some example strings:

print(is_palindrome("racecar")) # True

print(is_palindrome("Radar")) # True

print(is_palindrome("Python")) # False

print(is_palindrome("A man, a plan, a canal: Panama")) # True

Our palindrome checker correctly identifies these strings!

Handling Empty Strings

One edge case to consider is handling empty strings or strings with only one character. An empty string can technically be considered a palindrome since it reads the same forwards and backwards.

We can update our function to handle this:

def is_palindrome(string):

    # Empty string is considered palindrome
    if len(string) == 0:
        return True

    # Strings with one character are palindromes
    if len(string) == 1:
        return True

    # Rest of logic remains the same...

Now empty strings and single character strings will be identified as palindromes.

Improving Efficiency

Our current logic works fine, but it is not very efficient since we slice the string to reverse it.

Slicing creates a new string, which takes up additional memory. Instead, we can reverse the string in-place without slicing by using a for loop and swapping indices.

Here is an implementation with a more optimized approach:

def is_palindrome(string):

    left_index = 0
    right_index = len(string) - 1

    while left_index < right_index:

        if string[left_index] != string[right_index]:
            return False

        left_index += 1
        right_index -= 1

    return True

This implements a two-pointer technique that reverses the string in-place without slicing.

Ignoring Spaces and Case

Currently our function only ignores non-alphanumeric characters. We can update it to also ignore spaces and case-sensitivity.

Here’s one way to do this:

def is_palindrome(string):

    # Initialize left and right index
    left_index = 0
    right_index = len(string) - 1

    # Make string lowercase
    string = string.lower()

    # Remove spaces
    string = string.replace(" ", "")

    while left_index < right_index:

        if string[left_index] != string[right_index]:
            return False

        left_index += 1
        right_index -= 1

    return True

Now our function will properly identify palindromes regardless of case or extra spaces.

Function with Cleaner Logic

By breaking the processing and comparison steps into separate helper functions, we can improve modularity and clean up the main function logic:

import re

def clean_string(string):
    string = re.sub(r'\W+', '', string) # Remove non-alphanumeric
    string = string.lower() # Lowercase
    string = string.replace(" ", "") # Remove spaces
    return string

def reverse_string(string):
    return string[::-1]

def is_palindrome(string):

    cleaned = clean_string(string)
    reversed = reverse_string(cleaned)

    if cleaned == reversed:
        return True
    else:
        return False

This makes each step more modular and readable.

Palindrome Sentence Checker

So far our examples have looked only at single word palindromes. To check for palindrome sentences, we need to compare entire phrases as well as account for spaces between words.

Here is one approach:

import re

def clean_sentence(sentence):
    sentence = re.sub(r'\W+', '', sentence) # Remove non-alphanumerics
    sentence = sentence.lower()
    return sentence

def reverse_sentence(sentence):
    words = sentence.split(' ') # Split into words
    reversed_words = [word[::-1] for word in words] # Reverse each word
    return ' '.join(reversed_words) # Join words with spaces

def is_palindrome(sentence):

    cleaned = clean_sentence(sentence)
    reversed = reverse_sentence(cleaned)

    if cleaned == reversed:
        return True
    return False

This allows our palindrome checker to work on phrases with multiple words:

is_palindrome("racecar") # True
is_palindrome("A man, a plan, a canal: Panama") # True
is_palindrome("This is not a palindrome") # False

Recursion

We can also write a recursive palindrome checker function in Python. The recursive approach is:

  1. Base case - Empty string or one character string is palindrome.
  2. Recursion - Check first and last char, if equal call function on substring with first and last char removed.
  3. Build string back up recursively.

Here is an implementation:

def is_palindrome_recursive(string):

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

    # Recursive case
    if string[0] != string[-1]:
        return False

    return is_palindrome_recursive(string[1:-1])

Let’s test it:

print(is_palindrome_recursive("racecar")) # True
print(is_palindrome_recursive("python")) # False

The recursive approach can be slower due to repeated string slicing and function calls. But it provides an alternative, elegant palindrome checking solution.

Summary

In this guide, we learned several methods to check if a string is a palindrome in Python:

The key ideas include:

To handle sentence palindromes, split into words, reverse each word, then join and compare.

The recursive approach provides an elegant alternative using string slicing and recursion.

Palindrome checking makes for an interesting programming challenge in Python. The skills used can be applied to other string manipulation tasks as well.

Example Code

Here is the full palindrome checker code example:

import re

def is_palindrome(string):

    # Clean string
    string = re.sub(r'\W+', '', string)
    string = string.lower()

    # Initialize left and right indices
    left_index = 0
    right_index = len(string) - 1

    # Check for palindrome
    while left_index < right_index:

        if string[left_index] != string[right_index]:
            return False

        left_index += 1
        right_index -= 1

    return True


print(is_palindrome("racecar")) # True
print(is_palindrome("Radar")) # True
print(is_palindrome("Python")) # False

This implements the in-place two-pointer technique to check for palindromes in an efficient manner. Feel free to build upon this base code for your own applications.

Applications

Some examples of practical applications and use cases for palindrome checking functions in Python:

Overall, palindrome checkers make for a fun and enlightening Python programming exercise!

Conclusion

This guide covered a variety of methods and techniques for writing a palindrome checker program in Python. We looked at:

You should now have a solid foundational understanding of how to check for palindromes in Python. The skills and concepts can be applied to other string manipulation tasks you encounter as a programmer.

There are always opportunities for extension such as handling unicode characters, adding user interfaces, and more robust input handling. I hope you found this comprehensive guide helpful. Happy Python programming!