Search code examples
pythonfunctionpalindrome

Palindrome Function Python


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)

Solution

  • 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!