Exercise 6.1
← Previous Module 6: Functions Next →
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:

  • def defines a function with parameters.
  • re.sub uses regex to remove unwanted characters.
  • String slicing [::-1] reverses the string.
  • Functions make code reusable and modular.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top