0

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
3
  • 1
    str = to_alphanum(str).lower() Commented Oct 30, 2019 at 15:17
  • wow it's that easy lol, thank you! Commented Oct 30, 2019 at 15:19
  • Don't use str as a variable name. It is a builtin and shouldn't be shadowed. s is a common name for a generic string. You can also avoid the if condition: return True; else: return False by writing return condition. In your case, you can remove the last 4 lines and replace with return s==s[::-1] since s==s[::-1] will evaluate to True or False on its own. Commented Oct 30, 2019 at 15:27

1 Answer 1

2

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

str = to_alphanum(str).lower()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.