How to Check If a String Is a Palindrome in Python: Step-by-Step Guide

๐Ÿ”ฅ Read with Full Features on Our Website

Learn how to check if a string is a palindrome using Python. This beginner-friendly guide includes clear explanations, examples, and Python code to understand palindrome checking easily.

Published on 12 May 2025
By Rahul Kumar

๐Ÿง  What is a Palindrome?

๐Ÿ”ฅ Read with Full Features on Our Website

A palindrome is a word, number, phrase, or sequence that reads the same forward and backward.

๐Ÿ” Examples of Palindromes:

If you reverse these strings, they will still be the same!


Google Advertisement

๐Ÿ Python Program to Check for Palindrome

Let’s create a simple Python program that checks whether a given string is a palindrome.

# Program to check if a string is a palindrome

def is_palindrome(string):
    # Step 1: Convert the string to lowercase to ignore case sensitivity
    string = string.lower()

    # Step 2: Remove spaces from the string
    string = string.replace(" ", "")

    # Step 3: Reverse the string
    reversed_string = string[::-1]

    # Step 4: Compare original and reversed strings
    return string == reversed_string

# Example usage
user_input = input("Enter a string to check if it's a palindrome: ")

if is_palindrome(user_input):
    print(f"'{user_input}' is a palindrome!")
else:
    print(f"'{user_input}' is NOT a palindrome.")

๐Ÿงฉ Step-by-Step Explanation

๐Ÿ”น Step 1: Convert to Lowercase

string = string.lower()

๐Ÿ”น Step 2: Remove Spaces

string = string.replace(" ", "")
Google Advertisement

๐Ÿ”น Step 3: Reverse the String

reversed_string = string[::-1]

๐Ÿ”น Step 4: Compare Original and Reversed Strings

return string == reversed_string

๐Ÿงช More Examples

Let’s try some test cases with the function:

print(is_palindrome("Racecar"))       # True
print(is_palindrome("Python"))        # False
print(is_palindrome("A man a plan a canal Panama"))  # True
print(is_palindrome("12321"))         # True

๐Ÿ”„ Bonus: Palindrome Check Without Removing Spaces

If you want to check strictly character-by-character (including spaces), you can skip step 2.


Google Advertisement

๐Ÿš€ Why Use Python for This?


๐Ÿง  Common Questions

โ“ Can a sentence be a palindrome?

Yes! If you ignore spaces and case, sentences like "A man a plan a canal Panama" are palindromes.

โ“ What about numbers?

Yes! Numbers like 121 or 12321 are also palindromes.


๐ŸŽฏ Conclusion

Palindrome checking is one of the most common exercises in programming interviews and beginner tutorials. In Python, it becomes incredibly easy with string manipulation and slicing.

With just a few lines of code, you can create a program that checks whether a word, phrase, or number is a palindrome.

๐Ÿ‘‰ View Full Version on Main Website โ†—
๐Ÿ‘‰ Read Full Article on Website