不知道为什么while里面两个判断条件,如果交换一下顺序就是错误的
Topic source你这代码制表符这类的其他空格会测试失败的
if not s:
return ''
if s.isspace():
return ''
start = 0
end = len(s)
while start < end and s[start].isspace():
start = start + 1
while start < end and s[end-1].isspace():
end = end - 1
return s[start:end]
因为while 判断有顺序,如果位置调换会indexerror。
比如s = 1个空格,循环后start=0+1=1
but 下一次循环会先判断s[start]==' ',此时会发现s[1]超出索引范围,因为一个空格的s只有s[0]不存在s[1],于是indexerror
然而start<end在前面的话,循环会先判断start<end,发现1=1,判断不会继续。
- 1
Nectar
def trim(s):
start = 0
end = len(s)
while start < end and s[start] == ' ':
start = start + 1
while start < end and s[end - 1] == ' ':
end = end - 1
return s[start:end]