Determining if a string is a palindrome - Python

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

1

def is_palindrome(string): if string == string[::-1]: return True else: return False 

2

 def is_palindrome(string): if string == reversed(string): return True else: return False 
+5
source share
3 answers

reversed does not create a string, but a reverse object:

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

Thus, the string 'radar' does not compare with the reversed('radar') object. For it to work, you must ensure that the reversed object is actually evaluated:

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

u''.join(reversed(string)) inserts u'' between each of the characters in the string, and this causes the return string to turn into a string object.

+9
source

In the second, you need to make str from an instance of type reversed - this is not difficult:

 if string == ''.join(reversed(string)): 
+1
source

For strings:

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

For general iterations (including strings):

 def is_palindrome(iterable): """Return True if an iterable is a palindrome.""" if list(iteable) == list(reversed(iterable)) 
0
source

Source: https://habr.com/ru/post/1212401/


All Articles