def trim(s): if len(s) == 0: # 字符串为空直接返回 return '' elif s[0] != ' ' and s[-1] != ' ': # 首尾不存在空格直接返回 return s elif s[0] == ' ': # 字符串头存在空格则截断 return trim(s[1:]) else: return trim(s[:-1]) # 字符串尾存在空格则截断
if trim('hello ') != 'hello': print('测试失败') elif trim(' hello') != 'hello': print('测试失败') elif trim(' hello word ') != 'hello word': print('测试失败') elif trim(' ') != '': print('测试失败') elif trim(' ') != '': print('测试失败') else: print('测试成功')