Discuss / Python / 还是佩服递归的思路,我的有点笨

还是佩服递归的思路,我的有点笨

Topic source

_Liupy

#1 Created at ... [Delete] [Delete and Lock User]

#裁切字符串首尾的空格

def trim(string):

#数据类型检查
if not isinstance(string,(str)):
    print('输入数据错误')
    return string


#定义起始值
start = 0
#从左至右遍历字符串,求start值
for i in range(len(string)):
    if string[i] == ' ':
        start += 1
    else:
        break


#检查字符串内容是否全部是空格
if start == len(string):
    return ''


#若不全是空格,从右遍历字符串,求last值
else:
    #定义尾部值
    last = -1
    #当尾部没有空格的情况时
    if string[last] != ' ':
        return string[start:]
    #当尾部有空格的情况时    
    else:
        while string[last] == ' ':
            last  -= 1
        return string[start:last+1]

#测试 if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')


  • 1

Reply