Home > Back-end >  How to check for palindrome, ignoring special characters and case?
How to check for palindrome, ignoring special characters and case?

Time:01-24

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?

CodePudding user response:

You're only making this function case insensitive, but it seems you want to ignore spaces and punctuation too.

You can do this with the string module, like so:

#!/usr/bin/env python3

x = "Mr. Owl ate my metal worm"
y = "Some other string that isn't a palindrome"

def is_palindrome(value):
    value = "".join([x for x in value.lower() if x.isalnum()])
    return value == value[::-1]

print(is_palindrome(x))
print(is_palindrome(y))

result:

True
False

isalnum() only includes letters and numbers. So the full stop, spaces and any other punctuation are removed when checking the palindrome. (thanks jodag)

CodePudding user response:

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: ')))

CodePudding user response:

If you want to ignore . or space while checking palindrome, then try:

def is_palindrome(value):
    lower = value.lower()
    value = value.replace(" ","").replace(".", "")
    return value == value[::-1]
  •  Tags:  
  • Related