代码如下
这个代码是比较耿直的写法
def trim(s):
if s == '':
return s
elif s[0] == ' ':
return trim(s[1 : ])
elif s[-1] == ' ':
return trim(s[ : -1])
else:
return s
# 测试:
if trim('hello ') != 'hello':
print('1测试失败!')
elif trim(' hello') != 'hello':
print('2测试失败!')
elif trim(' hello ') != 'hello':
print('3测试失败!')
elif trim(' hello world ') != 'hello world':
print('4测试失败!')
elif trim('') != '':
print('5测试失败!')
elif trim(' ') != '':
print('6测试失败!')
else:
print('测试成功!')