Python: Check if a String is a Palindrome

Problem Statement:

Write a Python function that checks if a given string is a palindrome.

Solution Explanation:

  1. Convert the string to lowercase using .lower() to ensure case insensitivity.
  2. Remove spaces using .replace(" ", "") (optional, for handling phrases).
  3. Reverse the string using slicing [::-1].
  4. Compare the original and reversed strings.

Python Code:

def is_palindrome(s):
    s = s.lower().replace(" ", "")  # Convert to lowercase and remove spaces
    return s == s[::-1]  # Compare original with reversed

# Test cases
print(is_palindrome("madam"))     # Output: True
print(is_palindrome("racecar"))   # Output: True
print(is_palindrome("hello"))     # Output: False
print(is_palindrome("A man a plan a canal Panama"))  # Output: True

Example Output:

Input: “madam” → Output: True
Input: “hello” → Output: False
Input: “A man a plan a canal Panama” → Output: True

Leave a Reply