这些行:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index+1]
彼此不同意。如果新的最佳字符串是s[tempIndex:index+1]
该字符串,那么您应该在if条件中比较其长度。更改它们以彼此同意可以解决此问题:
if len(s[tempIndex:index+1]) > len(string):
string = s[tempIndex:index+1]