-1

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?

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
Karyala
  • 13
  • 6

2 Answers2

2

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)

Zhenhir
  • 1,157
  • 8
  • 13
  • 1
    It's probably worth mentioning that the asker's code is not, in fact, successfully case-insensitive, though there is an attempt. – CrazyChucky Jan 24 '22 at 06:37
  • 1
    True, I totally didn't see that. `return lower == lower[::-1]` would've fixed that one. – Zhenhir Jan 24 '22 at 06:42
  • 2
    Also worth pointing out that strings in python have `isalnum` method which allows you to replace the condition with `if x.isalnum()`. – jodag Jan 24 '22 at 06:48
  • Nice, i'd never used that one before, personally. – Zhenhir Jan 24 '22 at 06:59
1

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: ')))
Park
  • 2,446
  • 1
  • 16
  • 25
  • I have to check four Palindromes where I should give input and it should return me output as 'True" or 'False'. I have written the print statement like this - print(is_palindrome(input('Enter the value: '))), is_palindrome(input('Enter the value: ')), is_palindrome(input('Enter the value: ')), is_palindrome(input('Enter the value: '))). Instead of writing like this, how can I write it where it should ask me to 'Enter the Value' for 4 times and then stop. – Karyala Jan 24 '22 at 06:47
  • 1
    @Karyala A easiest way is that you can call each `is_palindrom()` function seperately in different `print()`s. – Park Jan 24 '22 at 06:49