Python palindrome program not working

后端 未结 7 878
后悔当初
后悔当初 2021-01-26 12:49

I\'ve written a simple program in python which checks if the sentence is palindrome. But I can\'t figure out why isn\'t it working. The results is always False. Does anyone know

7条回答
  •  半阙折子戏
    2021-01-26 13:31

    You're making this way more complicated than it has to be:

    def palindrome(sentence):
        sentence = sentence.strip().lower().replace(" ", "")
        return sentence == sentence[::-1]
    

    sentence[::-1] uses string slicing to reverse the characters in the string.

    A slightly more verbose solution that shows how the logic of the return statement above works:

    def palindrome(sentence):
        sentence = sentence.strip().lower().replace(" ", "")
        if sentence == sentence[::-1]:
            return True
        else:
            return False
    

提交回复
热议问题