Python slice exercise

Using slicing operations, to achieve a trim () function, remove spaces inclusive string, str not call the strip () Method:

def trim(s):
    if len(s) > 0:
        if s[0] == ' ':
            s = trim(s[1:])
        elif s[-1] == ' ':
            s = trim(s[:-1])
    return s

if trim('hello  ') != 'hello':
    print('测试失败_1!')
elif trim('  hello') != 'hello':
    print('测试失败_2!')
elif trim('  hello  ') != 'hello':
    print('测试失败_3!')
elif trim('  hello  world  ') != 'hello  world':
    print('测试失败_4!')
elif trim('') != '':
    print('测试失败_5!')
elif trim('    ') != '':
    print('测试失败_6!')
else:
    print('测试成功!')

That there is no better way to welcome communication

Published 110 original articles · won praise 2 · Views 3743

Guess you like

Origin blog.csdn.net/qq_40041064/article/details/105096234