Discuss / Python / 因为之前做过复习一次,利用前面的递归 ,最简单的代码

因为之前做过复习一次,利用前面的递归 ,最简单的代码

Topic source

#课后作业,创建一个自定义的函数,来去掉字符串前的空格

def trim(s): if not isinstance (s,str): raise TypeError('参数不是字符串') if s[:1]==' ': s = trim(s[1:]) #牢记标点符号,思路是对的,打错了也害死人 if s[-1:]==' ': s = trim(s[:-1])
return s

测试:

if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')


  • 1

Reply