def trim(s):
if len(s) > 0:
while s[-1:] == ' ':
s = s[:-1]
while s[0] == ' ':
s = s[1:]
return s
会有
File "d:\pyhthoncode\hello.py", line 5, in trim
while s[0] == ' ':
IndexError: string index out of range
这样的报错,
但是把这行s[0]变成s[:-1],就没错了,想问一下为什么不能写s[0]呢?
...全文
1663打赏收藏
求助python问题
写一个去字符串头尾空格的程序 def trim(s): if len(s) > 0: while s[-1:] == ' ': s = s[:-1] while s[0] == ' ': s = s[1:] return s 会有 File "d:\pyhthoncode\hello.py", line 5, in trim while s[0] == ' ': IndexError: string index out of range 这样的报错, 但是把这行s[0]变成s[:-1],就没错了