为什么我的代码回文仅适用于单个输入而不适用于多个输入?

问题描述 投票:0回答:6

回文是顺读和倒读时相同的单词或短语。例如:“bob”、“sees”或“never odd or Even”(忽略空格)。编写一个程序,其输入是单词或短语,并输出输入是否是回文。

我只猜对了一半。我的代码正在为鲍勃工作,并且看到了。 当输入“从不奇数或偶数”时,我的代码不起作用,它显示不是回文,但它应该是回文。

我在这里做错了什么?

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))
python palindrome
6个回答
0
投票

您正在将

word
new
进行比较,但为了生成
new
,您已删除了所有空格。


0
投票

这是因为

new = word.replace(" ", "")
行 -
word
与其中的空格保留在一起。您应该制作一个不带空格的
word
版本,反转它,然后将其与不带空格的
word
进行比较。

类似:

  word = str(input())
  spaceless_word = word.replace(" ", "")
  new = spaceless_word[::-1]

  if spaceless_word == new:
      print('{} is a palindrome'.format(word))
  else:
      print('{} is not a palindrome'.format(word))

0
投票

试试这个

word = str(input())
word = word.replace(" ", "")
new = word
new = new[::-1]

if word == new:
    print('{} is a palindrome'.format(word))
else:
    print('{} is not a palindrome'.format(word))

0
投票

我的答案,有点难看,但我只是不断添加一些东西,直到它是正确的。

inputs=str(input())
inputs_nospace=inputs.replace(' ', '')
inputs_reversed=inputs_nospace
inputs_reversed=inputs_reversed[::-1]
if inputs_reversed==inputs_nospace:
    print (inputs, 'is a palindrome')
else:
    print(inputs, 'is not a palindrome')

0
投票

虽然其他代码可能有效,但这是我用来确保一切正确的代码。我什至不必使用堆栈溢出。稀有

user_input = input() # get user input...
bare = user_input.strip().lower().split( ) # did this so even uppercase letters will be able to be palindromes
                                            #though the lab didn't even test that...
text = ''.join(bare) # this removes all space and will be used when compared with reverse_text
reverse_text = text[::-1] # U guessed it this is text reversed
if text != reverse_text: # simple if statement which checks to see if text == reverse_text
    print("not a palindrome:", user_input) # print statement to get full marks on lab
else: # i might be writing too much, but the else statement will only execute if text == reverse_text
    print("palindrome:", user_input) # and print statement to get full marks.

0
投票
og_word = str(input())
word = og_word
word = word.replace(" ", "")
new = word
new = new[::-1]

if word == new:
    print(f'palindrome: {og_word}')
else:
    print(f'not a palindrome: {og_word}')
© www.soinside.com 2019 - 2024. All rights reserved.