Palindrome Checker in Python
What is a Palindrome?
A palindrome is a word, number, phrase, or sequence that reads the same forward and backward.
Examples: madam, racecar, 121
Project Structure
palindrome_checker/
??? __init__.py
??? checker.py
??? main.py
Python Modules and Packages
__init__.py makes the folder a package.
We split our code into checker.py for logic and main.py for execution.
Logic in checker.py
1. Remove non-alphanumeric characters.
2. Convert to lowercase.
3. Compare string to its reverse.
Code: checker.py
Palindrome Checker in Python
def is_palindrome(text: str) -> bool:
if text is None:
return False
clean = ''.join(char.lower() for char in text if char.isalnum())
return clean == clean[::-1]
Code: main.py
from checker import is_palindrome
test_strings = ["Radar", "Level", "Hello", "Madam", "12321", "Python"]
for word in test_strings:
print(f"'{word}' is a palindrome? -> {is_palindrome(word)}")
Sample Output
'Radar' is a palindrome? -> True
'Level' is a palindrome? -> True
'Hello' is a palindrome? -> False
Advantages of Modular Approach
- Code Reusability
- Easy Maintenance
Palindrome Checker in Python
- Better Organization
Conclusion
- Palindromes can be checked easily using Python.
- Organizing code in packages improves clarity and reusability.