学习笔记之Python 切片:利用切片操作,实现一个trim()函数,去除字符串首尾的空格

需求: 

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

# Basic Version:
def trim(s):
    length = len(s)

    if length > 0:
        for i in range(length):
            if s[i] != ' ':
                break;
        j = length-1;
        while s[j] == ' ' and j >= i:
            j -= 1
        s = s[i:j+1]

    return s

# Improvement Recursion
def trim(s):
    if s[:1] != ' ' and s[-1:] != ' ':
        return s
    elif s[:1] == ' ':
        return trim(s[1:])
    else:
        return trim(s[:-1])

# Test:
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('测试成功!')
转载自: http://blog.csdn.net/Daniel960601/article/details/79174915

你可能感兴趣的:(学习笔记之Python 切片:利用切片操作,实现一个trim()函数,去除字符串首尾的空格)