L[ i:j ] 包含 i 不包含 j
L=list(range(100))==>0-99
tuple也可以切片:
字符串‘XXX’也是一个list:
def trim(s): for i in range(len(s)): if s[i]!=' ': break for j in range(-1,-len(s)-1): if s[j]!=' ': break return s[i:j] trim(' A b ')
UnboundLocalError: local variable 'j' referenced before assignment
注意:1、for i in range(len(s))不要写成for i in len()
2、for i,j in range(len(s))错误。i,j in (X,Y)
def trim(s): for i in range(len(s)): if s[i]!=' ': break for j in range(1,len(s)+1): if s[-j]!=' ': break return s[i:len(s)-j+1] trim(' A b c ')
问题1:range(-1,-len(s)-1):大的数写在了前面,没有执行for
问题2:return s[i,j]是不对的,一个正数、一个倒数