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

3qpi33ja  于 12个月前  发布在  Python
关注(0)|答案(6)|浏览(94)

回文是一个词或一个短语,是相同的,当读向前和向后。示例如下:“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))
vwhgwdsa

vwhgwdsa1#

您正在比较wordnew,但是为了生成new,您已经删除了所有空格。

vmdwslir

vmdwslir2#

这是因为行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))
avkwfej4

avkwfej43#

试试这个

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))
57hvy0tb

57hvy0tb4#

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

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

unguejic5#

虽然其他代码可能工作,但这是我用来确保一切正确的代码。我甚至不用使用堆栈溢出。罕见

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.
izj3ouym

izj3ouym6#

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

相关问题