Palindrome Detection in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For example, "racecar" is a palindrome because when you reverse the word, it still spells "racecar". In this challenge, you will write a function that checks if a given string is a palindrome.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") subgraph Lab Skills python/comments -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/booleans -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/lists -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/tuples -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/function_definition -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/importing_modules -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/using_packages -.-> lab-13704{{"`Palindrome Detection in Python`"}} python/standard_libraries -.-> lab-13704{{"`Palindrome Detection in Python`"}} end

Palindrome

Write a function palindrome(s) that takes a string s as its only parameter and returns True if s is a palindrome and False otherwise. Your function should ignore capitalization and non-alphanumeric characters when checking for palindromes.

To solve this problem, you can follow these steps:

  1. Use str.lower() to convert the string to lowercase.
  2. Use re.sub() to remove all non-alphanumeric characters from the string.
  3. Compare the resulting string with its reverse using slice notation.
from re import sub

def palindrome(s):
  s = sub('[\W_]', '', s.lower())
  return s == s[::-1]
palindrome('taco cat') ## True

Summary

In this challenge, you learned how to check if a given string is a palindrome. You used str.lower() and re.sub() to convert the string to lowercase and remove non-alphanumeric characters, and then compared the resulting string with its reverse using slice notation.

Other Python Tutorials you may like