n=len(s)-1 i=0 if n==-1: return s else: while i<=n and s[i]==' ': i+=1 while n>=0 and s[n]==' ': n-=1
#print(s[i:(n+1)],'pp') #if i>=n+1: # return '' #else: return s[i:(n+1)] 这样是对的。因为while里不加条件,s[i]会越界。越界之后根本就不会后面的判断,直接报错。至于前面的hello这类的不报错,是因为,s[i]==' ',这种,在出现字母的时候,while循环就终止了,自然不会越界。分享一下。纠结了一天呀,感觉自己好笨好笨,谢谢廖老师的分享,很受益
Sign in to make a reply
严肃的笨小孩
n=len(s)-1 i=0 if n==-1: return s else: while i<=n and s[i]==' ': i+=1 while n>=0 and s[n]==' ': n-=1