在递归的情况下,这种索引的含义是什么。
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
print("String isn't a palindrome!")
答案 0 :(得分:0)
如果您查看文档,则此表达式称为 slicing :Python: Slicing
您可以在此语法中添加三个参数。
第一个是序列的开始,第二个是结束(不包括在内),第三个是步骤。
放置否定参数时,意味着您从数组末尾开始计数。
所以:
s = "Hello World"
s = s[1:-1]
您将拥有:
s =“ ello Worl”
对于您的情况,递归地逐步到达字符串的 center ,并且每次您检查字符串是否仍然是回文式时都可以。当您只有一个或更少的字符时,它会返回True
,因为之前的所有内容都可以说您的字符串是回文