为什么我的代码总是给出相同的结果,即“字符串不是回文”

时间:2019-06-07 12:51:38

标签: python string comparison palindrome

我的代码总是给出相同的结果,即“字符串不是回文” 为什么会这样呢? 但字符串反转正常工作

original = input('enter string: ')
index = len(original) - 1
reverse_string =" "
while index >= 0 :
    reverse_string += original[index]
    index = index - 1

print('reverse string:', reverse_string)

if (reverse_string == original):
     print("it's a palindrome:")
else:
     print("it's not a palindrome:")

2 个答案:

答案 0 :(得分:2)

因为您的reverse_string以空格(即" ")开头:

original = input('enter string: ')
index = len(original) - 1
reverse_string = ""
while index >= 0 :
    reverse_string += original[index]
    index = index - 1

print('reverse string:', reverse_string)

if (reverse_string == original):
     print("it's a palindrome:")
else:
     print("it's not a palindrome:")

您也可以将其缩短为:

original = input('enter string: ')
if (original == original[::-1]): # [::-1] Returns the string in reverse.
     print("it's a palindrome:")
else:
     print("it's not a palindrome:")

根据评论,您还可以根据需要(通过olinox14)进一步缩短此时间:

original = input('enter string: ')
print("It's {}a palindrome".format("not " * (original!= original[::-1])))

或更易读(由Matthias撰写):

original = input('enter string: ')
print("It's{}a palindrome".format(' ' if original==original[::-1] else ' not '))

答案 1 :(得分:0)

您正在将reverse_string初始化为" ",因此此字符串将始终具有额外的空间,并且永远不会与原始字符串相等。

但是您可以将代码简化为:

reverse_string = ''.join(reversed(original))

或:

reverse_string = original[::-1]