How to Check if a String is Palindrome in Python
To check if a string is a palindrome in Python, compare the string with its reverse using
string == string[::-1]. If both are equal, the string reads the same forwards and backwards, so it is a palindrome.Syntax
Use the expression string == string[::-1] to check if a string is a palindrome.
string: the original text you want to check.string[::-1]: reverses the string using slicing.- Comparing both with
==returnsTrueif they are the same, meaning the string is a palindrome.
python
string = "level" if string == string[::-1]: print("Palindrome") else: print("Not palindrome")
Output
Palindrome
Example
This example checks if the input string is a palindrome and prints the result.
python
def is_palindrome(s: str) -> bool: return s == s[::-1] words = ["radar", "hello", "madam", "python"] for word in words: if is_palindrome(word): print(f"{word} is a palindrome") else: print(f"{word} is not a palindrome")
Output
radar is a palindrome
hello is not a palindrome
madam is a palindrome
python is not a palindrome
Common Pitfalls
Common mistakes when checking palindromes include:
- Not handling case differences (e.g., 'Radar' vs 'radar').
- Ignoring spaces or punctuation in phrases.
- Using loops or complicated logic instead of simple slicing.
To fix case issues, convert the string to lowercase first. To ignore spaces and punctuation, remove them before checking.
python
def is_palindrome_fixed(s: str) -> bool: cleaned = ''.join(c.lower() for c in s if c.isalnum()) return cleaned == cleaned[::-1] print(is_palindrome_fixed("A man, a plan, a canal, Panama")) # True print(is_palindrome_fixed("Hello")) # False
Output
True
False
Quick Reference
Summary tips for palindrome checking:
- Use
string[::-1]to reverse strings. - Convert to lowercase with
.lower()to ignore case. - Remove non-alphanumeric characters to handle phrases.
- Compare original and reversed strings for equality.
Key Takeaways
Use slicing
string[::-1] to reverse a string simply and efficiently.Compare the original string with its reversed version to check for palindrome.
Convert strings to lowercase to avoid case sensitivity issues.
Remove spaces and punctuation to correctly check phrases as palindromes.
Keep palindrome checks simple and readable using Python's string features.