HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

is_palindrome function that ignores whitespace and punctuation

Submitted by: @import:stackexchange-codereview··
0
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 string in 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.