#课后作业,创建一个自定义的函数,来去掉字符串前的空格
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('测试成功!')
Sign in to make a reply
黛柔时尚女鞋
#课后作业,创建一个自定义的函数,来去掉字符串前的空格
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('测试成功!')