def trim(S):
if S[:1]==" ":
return trim(S[1:])
elif S[-1:]==" ":
return trim(S[:-1])
return S
print(trim(" hhhhello "))
if s=="":
return s
while s[:1]==" ":
s=s[1:]
while s[-1:]==" ":
s=s[:-1]
在while循环之前进行判定,如果是空反馈原字符串即可。
Sign in to make a reply
杨森-ys
def trim(S):
if S[:1]==" ":
return trim(S[1:])
elif S[-1:]==" ":
return trim(S[:-1])
return S
print(trim(" hhhhello "))