Python reverse() for palindromes

五迷三道 提交于 2019-11-29 13:56:52

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.

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

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

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

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)
list(reverse( mystring )) == list( mystring )

or in the case of numbers

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

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")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!