去掉字符串前面空格:
def trim(s):
while s[0]==' ':
s=s[1:]
return s
print(trim(' hello'))
在网页python 3上运行,报错:
Traceback (most recent call last):
File "/app/main.py", line 22, in
elif trim('') != '':
File "/app/main.py", line 3, in trim
while s[0]==' ':
IndexError: string index out of range
改成下面代码后运行正常。不知道是为什么?
def trim(s):
while s[:1]==' ':
s=s[1:]
return s
print(trim(' hello'))