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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…