为什么我的代码回文仅适用于单个输入而不适用于多个输入?
回文是向前和向后阅读时相同的单词或短语。示例是:“鲍勃”,“ see se”,或“从不奇怪甚至”(忽略空间)。编写一个程序,其输入是单词或短语,并输出输入是否为palindrome。
我只得到这一半。我的代码正在为鲍勃(Bob)工作,并看到。 当输入是“永不奇怪甚至”我的代码不起作用时,它显示的不是回文,而应该是回文。
我在这里做错了什么?
word = str(input())
new = word.replace(" ", "")
new = new[::-1]
if word == new:
print('{} is a palindrome'.format(word))
else:
print('{} is not a palindrome'.format(word))
A palindrome is a word or a phrase that is the same when read both forward and backward. Examples are: "bob," "sees," or "never odd or even" (ignoring spaces). Write a program whose input is a word or phrase, and that outputs whether the input is a palindrome.
I'm only getting this half right. my code is working for bob, and sees.
When an input is "never odd or even" my code doesn't work it shows is not a palindrome but it should be a palindrome.
What am I doing wrong here?
word = str(input())
new = word.replace(" ", "")
new = new[::-1]
if word == new:
print('{} is a palindrome'.format(word))
else:
print('{} is not a palindrome'.format(word))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您正在将
Word
与新
进行比较,但是要生成new
您已删除了所有空格。You are comparing
word
withnew
, but to generatenew
you had removed all the spaces.这是因为line
new = word.replace(“”,“”)
-Word
与其中的空间保持在一起。您应该在没有空间的情况下制作Word
的版本,将其逆转,然后将其与No-SpaceWord
进行比较。像:
That is because of line
new = word.replace(" ", "")
- theword
is kept with the spaces in it. You should make a version ofword
with no spaces, reverse that, then compare it with the no-spacesword
.Something like:
尝试一下
try this
我的答案,有点难看,但我只是不断添加一些东西,直到它是正确的。
My answer, kinda ugly but I just kept adding stuff until it was right.
尽管其他代码可能有效,但这是我用来确保一切正确的代码。我什至不必使用堆栈溢出。稀有的
Although other code may work this is the code I used to make sure I got everything correct. I didn't even have to use stack overflow. Rare