Palindrome Checker
Source: Dev.to
What is a palindrome?
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).
Examples
| Input | Result |
|---|---|
racecar | True |
A man a plan a canal Panama | True |
hello | False |
Python solution
def is_palindrome(s):
"""
Checks if a string is a palindrome.
Ignores case and spaces.
"""
s = s.lower()
s = s.replace(" ", "")
return s == s[::-1]
# Test cases
print(is_palindrome("wilabaliw")) # True
print(is_palindrome("A man a plan a canal Panama")) # True
How it works
-
Convert to lowercase
s = s.lower()This ensures that
"Racecar"and"racecar"are treated as the same string. -
Remove spaces
s = s.replace(" ", "")Spaces are irrelevant for palindrome checking in phrases like
"A man a plan...". -
Compare with reversed string
return s == s[::-1]s[::-1]creates a reversed copy of the string. If the cleaned original string equals its reverse, the function returnsTrue; otherwise,False.
Happy coding!