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

个人的解法,稍微有点复杂,但是逻辑很清晰,请看以下代码。

def trim(s):
    if s=='' or s==' ':
        res = s
    else:
        s_revese = s[::-1]
        for i in range(len(s)):
            if s[i]!=' ':
                break
        for j in range(len(s)):
            if s_revese[j]!=' ':
                break
        index = len(s)-j
        res = s[i:index]
    return res
        

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

参考:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017269965565856
https://blog.csdn.net/daniel960601/article/details/79174915

你可能感兴趣的:(python,python)