Statement
Solution
Python Exercise 6.1: Palindrome Checker
Write a function that checks if text reads the same backward and forward.
Your program should:
- Define a function
is_palindrome(text)that takes a string and returns True if it's a palindrome. - Ignore case and non-alphanumeric characters.
- Test the function with user input.
Sample Interaction:
Input
Output
A man, a plan, a canal: Panama
True
Solution
Here is one way to check for palindromes using a function.
import re
def is_palindrome(text):
# Remove non-alphanumeric and convert to lowercase
cleaned = re.sub(r'[^a-zA-Z0-9]', '', text).lower()
# Check if it equals its reverse
return cleaned == cleaned[::-1]
# Test the function
text = input("Enter text: ")
print(is_palindrome(text))
Key Concepts:
defdefines a function with parameters.re.subuses regex to remove unwanted characters.- String slicing
[::-1]reverses the string. - Functions make code reusable and modular.
Test Console
Run code to see output...