Check for Palindrome in Python
Check for Palindrome in Python
A palindrome is a string that reads the same forwards and backwards, such as “racecar” or “madam”. This problem builds directly on string reversal.
Simple Solution
def is_palindrome(s):
return s == s[::-1]
# Examples
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
Case-Insensitive Check
def is_palindrome_ci(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome_ci("A man a plan a canal Panama")) # True
Alphanumeric Only
import re
def is_palindrome_clean(s):
s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
return s == s[::-1]
print(is_palindrome_clean("Was it a car or a cat I saw?")) # True
Key Takeaway
The core check is always s == s[::-1]. Real-world usage requires normalizing the string (lowercase, remove spaces/punctuation) before comparing.
(Visited 1 times, 1 visits today)