Discuss / Python / 作业

作业

Topic source

def trim(s):

#去首
while s[:1]==" ":
    s=s[1:]
    #当第一个为空格return 原来所有字符除去第一个字符
#去尾
while s[-1:]==" ":
    s=s[:-1]
    #当最后一个为空格时return 所有字符除去最后一个
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