How to Check If a String Is a Palindrome in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is a palindrome in Python. A palindrome is a sequence of characters that reads the same backward as forward, such as "madam" or "racecar".

The lab guides you through creating a Python script that defines a function is_palindrome to identify palindromes. This involves processing the input text by converting it to lowercase and removing spaces, then comparing the processed text with its reversed version. You will also learn how to test the function with example words.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/AdvancedTopicsGroup(["Advanced Topics"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/AdvancedTopicsGroup -.-> python/regular_expressions("Regular Expressions") subgraph Lab Skills python/strings -.-> lab-559574{{"How to Check If a String Is a Palindrome in Python"}} python/conditional_statements -.-> lab-559574{{"How to Check If a String Is a Palindrome in Python"}} python/function_definition -.-> lab-559574{{"How to Check If a String Is a Palindrome in Python"}} python/regular_expressions -.-> lab-559574{{"How to Check If a String Is a Palindrome in Python"}} end

Define Palindromes

In this step, we'll explore the concept of palindromes and how to identify them using Python. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Examples include "madam", "racecar", and "level".

To begin, let's create a Python script to define what a palindrome is.

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named palindrome.py in the ~/project directory.

    You can create a new file by right-clicking in the Explorer panel (usually on the left side) and selecting "New File". Make sure you save the file as palindrome.py in the ~/project directory.

  3. Add the following Python code to the palindrome.py file:

    def is_palindrome(text):
        processed_text = ''.join(text.lower().split())
        return processed_text == processed_text[::-1]
    
    ## Example usage
    word = "madam"
    if is_palindrome(word):
        print(f"'{word}' is a palindrome")
    else:
        print(f"'{word}' is not a palindrome")

    Let's break down this code:

    • def is_palindrome(text):: This line defines a function named is_palindrome that takes a string text as input.
    • processed_text = ''.join(text.lower().split()): This line prepares the input text for palindrome checking. It first converts the text to lowercase using .lower() and then removes any spaces using .split() to split the string into a list of words, and ''.join() to join the words back into a single string without spaces.
    • return processed_text == processed_text[::-1]: This line compares the processed text with its reverse. processed_text[::-1] creates a reversed copy of the string. If the processed text is the same as its reverse, the function returns True (it's a palindrome); otherwise, it returns False.
    • The lines after the function definition are example usage. It calls the is_palindrome function with the word "madam" and prints whether it's a palindrome or not.
  4. Now, let's run the script. Open a terminal in the WebIDE. You can usually find a terminal tab at the bottom of the VS Code interface, or you can open a new one via the menu: Terminal -> New Terminal.

  5. In the terminal, navigate to the ~/project directory (if you're not already there):

    cd ~/project
  6. Execute the Python script:

    python palindrome.py
  7. You should see the following output:

    'madam' is a palindrome

    This confirms that our script correctly identifies "madam" as a palindrome.

Reverse and Compare

In this step, we'll delve deeper into how the is_palindrome function works by explicitly reversing the input string and then comparing it to the original. This will give you a clearer understanding of the palindrome identification process.

  1. Open the palindrome.py file in the VS Code editor. This is the same file you created in the previous step.

  2. Modify the is_palindrome function in palindrome.py to reverse the string explicitly:

    def is_palindrome(text):
        processed_text = ''.join(text.lower().split())
        reversed_text = processed_text[::-1]  ## Explicitly reverse the string
        return processed_text == reversed_text
    
    ## Example usage
    word = "madam"
    if is_palindrome(word):
        print(f"'{word}' is a palindrome")
    else:
        print(f"'{word}' is not a palindrome")
    
    word2 = "hello"
    if is_palindrome(word2):
        print(f"'{word2}' is a palindrome")
    else:
        print(f"'{word2}' is not a palindrome")

    Here's what changed:

    • reversed_text = processed_text[::-1]: This line creates a reversed copy of the processed_text string and assigns it to the variable reversed_text.
    • return processed_text == reversed_text: This line now compares the original processed text with the explicitly reversed text.
    • Added a second example with the word "hello" to demonstrate a non-palindrome.
  3. Save the changes to palindrome.py.

  4. Run the script again in the terminal:

    python palindrome.py
  5. You should now see the following output:

    'madam' is a palindrome
    'hello' is not a palindrome

    This output confirms that the script correctly identifies both palindromes and non-palindromes. By explicitly reversing the string, we've made the logic of the is_palindrome function more transparent.

Ignore Case and Spaces

In this step, we'll enhance our is_palindrome function to handle phrases that are palindromes but contain spaces and mixed-case letters. For example, "A man, a plan, a canal: Panama" is a palindrome if we ignore the spaces, punctuation, and case.

  1. Open the palindrome.py file in the VS Code editor.

  2. Modify the is_palindrome function in palindrome.py to ignore case and spaces:

    import re
    
    def is_palindrome(text):
        processed_text = re.sub(r'[^a-zA-Z]', '', text).lower()
        reversed_text = processed_text[::-1]
        return processed_text == reversed_text
    
    ## Example usage
    word1 = "A man, a plan, a canal: Panama"
    if is_palindrome(word1):
        print(f"'{word1}' is a palindrome")
    else:
        print(f"'{word1}' is not a palindrome")
    
    word2 = "Racecar"
    if is_palindrome(word2):
        print(f"'{word2}' is a palindrome")
    else:
        print(f"'{word2}' is not a palindrome")
    
    word3 = "hello"
    if is_palindrome(word3):
        print(f"'{word3}' is a palindrome")
    else:
        print(f"'{word3}' is not a palindrome")

    Let's break down the changes:

    • import re: This line imports the re module, which provides regular expression operations.
    • processed_text = re.sub(r'[^a-zA-Z]', '', text).lower(): This line now uses a regular expression to remove any characters that are not letters (a-z, A-Z) from the input text. re.sub(r'[^a-zA-Z]', '', text) replaces all non-letter characters with an empty string, effectively removing them. Then, .lower() converts the resulting string to lowercase.
    • We've added example usages with "A man, a plan, a canal: Panama", "Racecar", and "hello" to test the updated function.
  3. Save the changes to palindrome.py.

  4. Run the script again in the terminal:

    python palindrome.py
  5. You should now see the following output:

    'A man, a plan, a canal: Panama' is a palindrome
    'Racecar' is a palindrome
    'hello' is not a palindrome

    This output confirms that the script now correctly identifies palindromes even with spaces, punctuation, and mixed-case letters. The regular expression effectively cleans the input text, allowing for accurate palindrome detection.

Summary

In this lab, we began by exploring the concept of palindromes, which are strings that read the same backward as forward. We then created a Python script named palindrome.py containing a function is_palindrome(text) to identify palindromes.

The is_palindrome function first preprocesses the input text by converting it to lowercase and removing spaces. It then compares the processed text with its reversed version to determine if it's a palindrome, returning True if it is and False otherwise. The script also includes example usage demonstrating how to call the function and print the result.