patternpythonModerate
is_palindrome function that ignores whitespace and punctuation
Viewed 0 times
punctuationwhitespaceis_palindromefunctionignoresthatand
Problem
from string import punctuation, ascii_lowercase
def is_palindrome(string):
"""Return True if string is a palindrome,
ignoring whitespaces and punctuation.
"""
new = ""
for char in string:
lc = char.lower()
for x in lc:
if x in ascii_lowercase:
new += x
return new[::-1] == new
# string = "Was it a rat I saw?"
# print(is_palindrome(string))Solution
- You are unnecessarily importing
punctuation
- Avoid reassigning module names such as
stringin your code
- A list comprehension would be a simpler way of filtering out the data you don't want
from string import ascii_letters
def is_palindrome(candidate):
"""
Returns True if candidate is a palindrome, ignoring whitespaces and punctuation.
"""
stripped = [char.lower() for char in candidate if char in ascii_letters]
return stripped == stripped[::-1]Code Snippets
from string import ascii_letters
def is_palindrome(candidate):
"""
Returns True if candidate is a palindrome, ignoring whitespaces and punctuation.
"""
stripped = [char.lower() for char in candidate if char in ascii_letters]
return stripped == stripped[::-1]Context
StackExchange Code Review Q#31928, answer score: 11
Revisions (0)
No revisions yet.