切片:练习

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

def trim(s):
    n = len(s)
    a, b = 0, -1
    if s == '':
        return s
    if len([])
    while a < n:
        if s[a] != ' ':    #''之间有一个空格
            print('a:%s'%a)
            break
        a=a+1

    while b < 0:
        if s[b] != ' ':
             print('b:%s'%b)
             break
        b=b-1

    if b==-1:
        return s[a:]
    else:
        print('sss')
        b=b+1
        return s[a:b]
# 测试:
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测试失败!')
else:
    print('测试成功!')

  其中还有一个条件未成功,多个空格变成一个空格

elif trim('    ') != '':
    print('测试失败!')

  

 

posted @ 2018-04-27 20:26  Gringer  阅读(311)  评论(0编辑  收藏  举报