Python Program to Check Whether a String is Palindrome or Not

Updated on December 5, 2024
Check whether a string is palindrome or not header image

Introduction

A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). This characteristic makes palindrome checking an interesting problem in computer science and software development, often used in coding interviews and educational exercises.

In this article, you will learn how to check if a string is a palindrome using Python. Examples will guide you through different approaches, from basic iteration techniques to more Pythonic solutions, demonstrating efficiency and readability in code.

Checking Palindromes Using String Slicing

Simple Reverse Check

  1. Read the input string from the user.

  2. Convert the string to a standard format by making it lowercase and removing spaces.

  3. Compare the original formatted string to its reverse.

    python
    def is_palindrome(s):
        formatted_str = s.replace(" ", "").lower()
        return formatted_str == formatted_str[::-1]
    
    # Example usage:
    user_input = "A man a plan a canal Panama"
    print("Is palindrome:", is_palindrome(user_input))
    

    This code snippet defines a function is_palindrome that removes spaces and converts the string to lowercase to normalize it. It then checks if this formatted string is the same forwards and backwards using slicing ([::-1]).

Using string methods for formatting

  1. Utilize more string methods to handle punctuation and other non-alphabetic characters.

  2. Employ the same reverse check method for palindrome evaluation.

    python
    import string
    
    def is_palindrome(s):
        translator = str.maketrans('', '', string.punctuation)
        formatted_str = s.translate(translator).replace(" ", "").lower()
        return formatted_str == formatted_str[::-1]
    
    # Example usage:
    user_input = "No 'x' in Nixon."
    print("Is palindrome:", is_palindrome(user_input))
    

    This example extends the is_palindrome function by removing punctuation using str.maketrans and string.punctuation. This allows checking strings with commas, periods, and other punctuation marks.

Checking Palindromes with Iterative Approach

Manual Character Comparison

  1. Normalize the input string by removing non-alphabetic characters and converting it to lowercase.

  2. Use a loop to compare characters from the start and the end moving towards the center.

    python
    def is_palindrome(s):
        s = ''.join([char.lower() for char in s if char.isalnum()])
        left, right = 0, len(s) - 1
        while left < right:
            if s[left] != s[right]:
                return False
            left, right = left + 1, right - 1
        return True
    
    # Example usage:
    user_input = "Was it a car or a cat I saw?"
    print("Is palindrome:", is_palindrome(user_input))
    

    This function manually compares characters at symmetric positions from the outside inwards. It uses a loop to increment and decrement pointers, stopping if a mismatch is found or the pointers cross.

Conclusion

Checking whether a string is a palindrome in Python demonstrates fundamental string manipulation and iteration techniques. From simple reverse checks to complex punctuations handling and manual comparisons, Python's flexibility allows for both readable and efficient solutions. With the techniques discussed, you can efficiently determine if any given string is a palindrome, applicable in many practical and educational contexts. Whether for fun puzzles, coding interviews, or data processing, mastering these methods ensures robust and effective string manipulation capabilities.