适用于回文的Python reverse() [英] Python reverse() for palindromes

查看:73
本文介绍了适用于回文的Python reverse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚开始使用python,并且正在尝试将用户输入的字符串作为回文测试.我的代码是:

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

这总是返回false,因为y变成类似于<reversed object at 0x00E16EF0>的东西,而不是相反的字符串. 我对什么一无所知?您将如何编码此问题?

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?

推荐答案

尝试y = x[::-1].这使用拼接来获取字符串的反序.

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

reversed(x)返回一个迭代器,该迭代器以相反的顺序遍历字符串中的字符,不是一个可以直接与x比较的字符串.

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.

这篇关于适用于回文的Python reverse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆