利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

首先判断字符串的长度是否为0,如果是,直接返回字符串

第二,循环判断字符串的首部是否有空格,如果有,去掉空格,再判断字符串的长度是否为0,如果是,直接返回字符串

第三,循环判断字符串的尾部是否有空格,如果有,去掉空格,再判断字符串的长度是否为0,如果是,直接返回字符串

最后,返回字符串

代码:

def trim(s):
    if len(s) == 0:
        return s

    while s[0] == ' ':
        s = s[1:]
        if len(s) == 0:
            return s

    while s[-1] == ' ':
        s = s[:-1]
        if len(s) == 0:
            return s

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

本文来自博客园,作者:anthinia,转载请注明原文链接:https://www.cnblogs.com/anthinia/p/10930212.html

原文地址:https://www.cnblogs.com/anthinia/p/10930212.html