用递归及python切片的方法,实现python的strip()方法,去掉字符串首尾的空格

直接附上代码及测试:

# 用递归及python切片的方法,实现python的strip()方法
def trim(s):
    if s[:1] != ' ' and s[-1:] != ' ':  # 字符串前后都没有空格,返回该字符串
        return s
    elif s[:1] == ' ':
        return trim(s[1:])  # 字符串第一个位置为空,返回第二个位置及后面的字符串
    else:
        return trim(s[:-1])  # 字符串最后一个位置为空,返回倒数第二个位置及前面的字符串


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('测试成功!')

猜你喜欢

转载自blog.csdn.net/wangyuanshun/article/details/81219154