def trim(s):
n=len(s)
while n >= 0:
if s[:1] == ' ':
s=s[1:]
if s[-1:] == ' ':
s=s[:-1]
n= n - 1
return s
测试trim(' ')程序报错字符串索引越界,把第二个if修改为elif
抱歉看错了,代码是可行的QAQ
Sign in to make a reply
快乐水的好朋友
def trim(s):
n=len(s)
while n >= 0:
if s[:1] == ' ':
s=s[1:]
if s[-1:] == ' ':
s=s[:-1]
n= n - 1
return s