1 def trim(s): 2 if s[:1] == ' ': 3 return trim(s[1:]) 4 if s[-1:] == ' ': 5 return trim(s[:-1]) 6 return s 7 8 # 测试: 9 if trim('hello ') != 'hello': 10 print('测试失败!') 11 elif trim(' hello') != 'hello': 12 print('测试失败!') 13 elif trim(' hello ') != 'hello': 14 print('测试失败!') 15 elif trim(' hello world ') != 'hello world': 16 print('测试失败!') 17 elif trim('') != '': 18 print('测试失败!') 19 elif trim(' ') != '': 20 print('测试失败!') 21 else: 22 print('测试成功!')