0

I'm trying to write a function that will tell me if the inputted word or phrase is a palindrome. So far my code works but only for single words. How would I make it so that if I enter something with a space in it like 'race car' or 'live not on evil' the function will return true? Other questions on this page explain how to do it with one words but not with multiple words and spaces. Here what I have so far...

def isPalindrome(inString):
    if inString[::-1] == inString:
        return True
    else:
        return False

print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
print isPalindrome(inString)
Josh
  • 27
  • 8
  • @willnx: Correct me if I'm wrong. I think your link goes to a question about seeing if a word is a palindrome, but this one is seeing if a whole sentence is. That may sound ridiculous to make the distinction, but "madam im adam" wouldn't work in your link. (If I read that right.) – zondo Mar 11 '16 at 03:39

3 Answers3

0

You just need to split it by the spaces and join again:

def isPalindrome(inString):
    inString = "".join(inString.split())
    return inString[::-1] == inString
zondo
  • 19,901
  • 8
  • 44
  • 83
0

You could add the characters of the string to a list if the character is not a space. Here is the code:

def isPalindrome(inString):
    if inString[::-1] == inString:
        return True
    else:
        return False

print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
inList = [x.lower() for x in inString if x != " "]  #if the character in inString is not a space add it to inList, this also make the letters all lower case to accept multiple case strings.
print isPalindrome(inList)

Output of the famous palindrome "A man a plan a canal panama" is True. Hope this helps!

Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
0

Slightly different approach. Just remove spaces:

def isPalindrome(inString):
    inString = inString.replace(" ", "")
    return inString == inString[::-1]
idjaw
  • 25,487
  • 7
  • 64
  • 83