-1

I wasn't sure what to title it, but I'm writing a function that checks if a phrase is a palindrome or not. If something is capitalized or not doesn't matter and if there are other characters it will remove them. If the string is the same forwards and backwards (that's what a palindrome is) then it will be a Boolean True, and a Boolean False if it isn't. For example:

is_palindrome('ta.cocat')
#It would return
True

is_palidrome('Tacocat')
#It would return
True

is_palindrome('tacodog')
#It would return
False
I've written code that will take out extra characters, but I can't figure out how to make it that capitalization doesn't matter.

#Strip non-alpha
def to_alphanum(str):
  return ''.join([char for char in str if char.isalnum()]) 

#Palindromes
def is_palindrome(str):
  str = to_alphanum(str)
  if(str==str[::-1]):
    return True
  else:
    return False
#Here's examples about what it returns
is_palindrome('taco.cat')
True

is_palindrome('Tacocat')
>>> False
KittyWhale
  • 89
  • 7
  • 1
    You need [casefold](https://docs.python.org/3/library/stdtypes.html#str.casefold) – chthonicdaemon Nov 05 '19 at 04:15
  • 1
    Possible duplicate of [How do I do a case-insensitive string comparison?](https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison) – AMC Nov 05 '19 at 06:04

2 Answers2

0

just use the lower function on your input string, so that case doesnt matters in your function

str = to_alphanum(str).lower()
  • 1
    I believe that `casefold` is a more appropriate choice, see the comment by @chtonicdaemon. – AMC Nov 05 '19 at 06:04
0

You can simply use:

def isPalindrome(s): 
    s = to_alphanum(s).lower()
    rev = s[::-1]

    # Checking if both string are equal or not 
    if (s == rev): 
        return True
    return False

s1 = "malayalam"
>>> isPalindrome(s1)
True
pissall
  • 7,109
  • 2
  • 25
  • 45