方法1 切片
while s[:1] == " ": #不能写成s[0],当s=""时,报错“string index out of range”
s = s[1:]
while s[-1:] == " ":
s = s[:-1]
return s
方法2 递归
if s[:1]==' ':
return trim(s[1:])
elif s[-1:]== ' ':
return trim(s[:-1])
else:
递归太强了吧
递归不能解决纯空格的字符串
Sign in to make a reply
狼叔叔
方法1 切片
while s[:1] == " ": #不能写成s[0],当s=""时,报错“string index out of range”
s = s[1:]
while s[-1:] == " ":
s = s[:-1]
return s
方法2 递归
if s[:1]==' ':
return trim(s[1:])
elif s[-1:]== ' ':
return trim(s[:-1])
else:
return s