Python: Check Palindrome String

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

In this blog post, we will learn how to write a Python program to check if a given string is a palindrome.

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward and forward (ignoring spaces, punctuation, and capitalization). Examples include "radar", "level", and "deified". In this blog post, we'll create a Python program to check if a given string is a palindrome.

2. Program Overview

Our program will take a string input from the user. 

It will then remove any non-alphanumeric characters and convert the string to lowercase to ensure consistent comparison. 

The program will compare the original string with its reverse to determine if it's a palindrome.

3. Code Program

def is_palindrome(s):
    # Convert the string to lowercase and remove non-alphanumeric characters
    cleaned_string = ''.join(e for e in s if e.isalnum()).lower()

    # Compare the cleaned string with its reverse
    return cleaned_string == cleaned_string[::-1]

# Input string from user
user_input = input("Enter a string: ")

# Check and display if the string is a palindrome
if is_palindrome(user_input):
    print("The given string is a palindrome!")
else:
    print("The given string is not a palindrome!")

Output:

For the input "A man, a plan, a canal, Panama", the program will output: "The given string is a palindrome!"

4. Step By Step Explanation

1. The function is_palindrome first removes any character from the string that isn't alphanumeric using a combination of a join method and a for loop with an if condition.

2. It then converts the cleaned string to lowercase.

3. The function compares this cleaned string with its reverse (achieved with [::-1] slicing) to determine if it's a palindrome.

4. The main part of the program takes the user input, processes it through this function, and prints the appropriate message based on the result.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare