is "lst[1:-1]" any different from "lst[1:]"? in this situation:
def is_pal(string):
if len(string) < 2:
return True
elif string[0] != string[-1]:
return False
else:
return is_pal(string[1:-1])
The code is Checking whether string is palindrome.
-1 is exclusive, meaning [1:-1] will return the whole string except for the first (0) and the last characters.
BTW you can just reverse the text and check it that way:
def is_pal(string):
return string[::-1] == string
consider a string,
s = "abcdef"
s[1:] = "bcdef"
s[1:-1] = "bcde"
To check whether the given string is palindrome or not, just compare the given string s
with string s[::-1]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.