Search code examples
pythonpalindrome

How to check for palindrome, ignoring special characters and case?


I have a palindrome: 'Mr. Owl ate my metal worm'

Below is my code giving me output as False.

def is_palindrome(value):
    lower = value.lower()
    return value == value[::-1]

print(is_palindrome(input('Enter the value: ')))

How can I improve my code, making it ignore case, spaces, and special characters, to identify the above palindrome and give the output as True?


Solution

  • I found that there are a few issues in your code.

    • First, you assigned value.lower() to lower but you did not use lower.
    • Second, you have to process special characters and spaces to consider only normal characters for Palindrome.

    I edited your code so that it returns True, as follows:

    def is_palindrome(value):
        value = ''.join(value.split())
        value = value.replace('.', '')
        value = value.lower()
        return value == value[::-1] # mrowlatemymetalworm
    
    print(is_palindrome(input('Enter the value: ')))