Determining if string is palindrome

前端 未结 4 798
Happy的楠姐
Happy的楠姐 2020-12-20 18:43

I wrote two simple functions to determine if a string is a palindrome. I thought they were equivalent, but 2 doesn\'t work. Why is this?

1



        
相关标签:
4条回答
  • 2020-12-20 19:17

    In the second one, you need to make a str from the reversed type instance -- it's not hard:

    if string == ''.join(reversed(string)):
    
    0 讨论(0)
  • 2020-12-20 19:22

    reversed doesn't create a string but a 'reversed' object:

    >>> reversed('radar')
    <reversed object at 0x1102f99d0>
    

    As such, the string 'radar' does not compare equal to the object reversed('radar'). To make it work, you need to make sure the reversed object is actually evaluated:

    def is_palindrome(string):
        if string == u''.join(reversed(string)):
            return True
        else:
            return False
    

    The u''.join(reversed(string)) inserts u'' in between each of the characters in the string and this leads to the reversed string being turned into a string object.

    0 讨论(0)
  • 2020-12-20 19:35

    For strings:

    def is_palindrome(s):
        """Return True if a string is a palindrome."""
        return s == s[::-1]
    

    For general iterables (including strings):

    def is_palindrome(iterable):
        """Return True if an iterable is a palindrome."""
        if list(iteable) == list(reversed(iterable))
    
    0 讨论(0)
  • 2020-12-20 19:35
    str = input("Enter a string")
    print("\n".join(["Inserted string is" + "NOT"*((str[::-1])!=str)+ " a palindrome"]))
    
    0 讨论(0)
提交回复
热议问题