为什么我的Python palindrome-function失败了?[重复]

问题描述 投票:0回答:1
def is_palindrome(input_string):
# We'll create two strings, to compare them
   if input_string[0:] == input_string[-1:]:
      return True
   else:
      return False

预期输出如下。

print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True

目前所有的情况下我都得到了False. 我知道我的拼接可能在-1上有问题,我已经试过把冒号换掉,但没有用。

python python-3.x string while-loop palindrome
1个回答
0
投票

按照你现在的做法,你是将所有的字母与最后一个字母进行比较。

>>> a = [1,2,3]
>>> a[-1:]
[3]
>>> a[0:]
[1,2,3]

但这不是你反转一个字符串或任何可迭代的方式。 步长索引应该是负数。

>>> a = [1,2,3]
>>> a[::-1]
[3,2,1]

所以你只是想把原来的字符串和那个字符串进行比较。


0
投票

另外,我觉得你要把前面的空格去掉,把字母降低或提高。

l = ['Never Odd or Even', 'abc', 'kayak']

def isit(s):
    s = s.replace(' ', '').lower()
    return s == s[::-1]

for e in l:
    isit(e)


True
False
True
© www.soinside.com 2019 - 2024. All rights reserved.