Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reverse() for palindromes

I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:

x=input('Please insert a word')
y=reversed(x)
if x==y:
    print('Is a palindrome')
else:
    print('Is not a palindrome')

This always returns false because y becomes something like <reversed object at 0x00E16EF0> instead of the reversed string. What am I being ignorant about? How would you go about coding this problem?

like image 692
Matthew Sainsbury Avatar asked Mar 05 '11 08:03

Matthew Sainsbury


2 Answers

Try y = x[::-1]. This uses splicing to get the reverse of the string.

reversed(x) returns an iterator for looping over the characters in the string in reverse order, not a string you can directly compare to x.

like image 183
Justin Ardini Avatar answered Nov 15 '22 08:11

Justin Ardini


reversed returns an iterator, which you can make into a string using the join method:

y = ''.join(reversed(x))
like image 40
user470379 Avatar answered Nov 15 '22 07:11

user470379