Python Program to Check Palindrome: A Beginner’s Guide

  • Post author:
  • Post comments:0 Comments
  • Reading time:13 mins read

A palindrome is a word, phrase, number, or another sequence of characters that reads the same forwards and backward. For example, the word “racecar” is a palindrome because it is spelled the same way forwards and backward.

To check whether a string is a palindrome or not, we can compare the string to its reverse. If the string and its reverse are the same, then the string is a palindrome. Otherwise, it is not a palindrome.

Here is an example of how this can be implemented in Python:


def is_palindrome(string):
    # Remove all non-alphanumeric characters and convert to lowercase
    clean_string = ''.join(c for c in string if c.isalnum()).lower()
    
    # Check if the string is a palindrome
    return clean_string == clean_string[::-1]

# Test the function
print(is_palindrome('A man, a plan, a canal: Panama'))  # True
print(is_palindrome('racecar'))  # True
print(is_palindrome('hello'))  # False

In this program, we define a function is_palindrome that takes a string as input and returns a boolean value indicating whether the string is a palindrome or not. The function first removes all non-alphanumeric characters and converts the remaining characters to lowercase. It then checks if the cleaned string is equal to its reverse.

The function is then tested using three test cases: a palindrome containing punctuation and mixed case, a simple palindrome, and a non-palindrome.

In conclusion, a palindrome is a word, phrase, number, or another sequence of characters that reads the same forwards and backward. To check whether a string is a palindrome or not, we can compare the string to its reverse. If the string and its reverse are the same, then the string is a palindrome. Otherwise, it is not a palindrome. This can be easily implemented in Python using a simple function that compares the input string to its reverse. Palindromes can be useful in various contexts, such as in word games, programming challenges, and data validation.

Publisher

Publisher

Publisher @ideasorblogs

Leave a Reply