Matthew Sainsbury
Matthew Sainsbury

Reputation: 1488

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?

Upvotes: 6

Views: 21430

Answers (7)

Vineeta Pandey
Vineeta Pandey

Reputation: 1

Try this code to find whether original & reverse are same or not:-

if a == a[::-1]: 

#this will reverse the given string, eventually will give you idea if the given string is palindrome or not.

Upvotes: 0

Johanna Fulghum
Johanna Fulghum

Reputation: 1

Try this code:

def palindrome(string):
    i = 0 
    while i < len(string):
        if string[i] != string[(len(string) - 1) - i]:
            return False
        i += 1
    return True

print palindrome("hannah")

Upvotes: 0

Richard Hayes
Richard Hayes

Reputation: 155

list(reverse( mystring )) == list( mystring )

or in the case of numbers

list(reverse( str(mystring) )) == list( str(mystring) )

Upvotes: 0

Uruk-hai
Uruk-hai

Reputation: 659

Try this code.

def pal(name):
        sto_1 = []
        for i in name:
                sto_1.append(i)

        sto_2 = []
        for i in sto_1[::-1]:
                sto_2.append(i)

        for i in range(len(name)):
                if sto_1[i] == sto_2[i]:
                        return "".join(sto_1), "".join(sto_2)
                else:
                        return "no luck"

name = raw_input("Enter the word :")
print pal(name)

Upvotes: 0

mirandalol
mirandalol

Reputation: 465

For future reference, a lambda from the answers above for quick palindrome check:

isPali = lambda num: str(num) == str(num)[::-1]

example use:

isPali(9009) #returns True

Upvotes: 2

user470379
user470379

Reputation: 4887

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

y = ''.join(reversed(x))

Upvotes: 8

Justin Ardini
Justin Ardini

Reputation: 9866

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.

Upvotes: 19

Related Questions