Reputation: 9054
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
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
Upvotes: 6
Views: 370
Reputation: 1
str = input("Enter a string")
print("\n".join(["Inserted string is" + "NOT"*((str[::-1])!=str)+ " a palindrome"]))
Upvotes: 0
Reputation: 44475
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))
Upvotes: 0
Reputation: 881575
In the second one, you need to make a str
from the reversed
type instance -- it's not hard:
if string == ''.join(reversed(string)):
Upvotes: 1
Reputation: 122336
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.
Upvotes: 10