Palindrome Ignoring Punctuation

Category: Python Basics

Write a program that checks whether a given string is a palindrome, ignoring punctuation, whitespace, and letter casing.

Example:

Input: "A man, a plan, a canal: Panama" 

Output: True

First, remove all punctuation and whitespace from the string and convert it to lower case. Then, compare the resulting string with its reverse to check if the input string is a palindrome.

import re

def is_palindrome(s):
s = re.sub(r'\W+', '', s).lower()
return s == s[::-1]

print(is_palindrome("A man, a plan, a canal: Panama")) # Outputs: True

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!