def trim(str): n = 0 m = -1 while n < len(str): if str[n:n+1] == " ": n = n + 1 else: break while abs(m)<len(str): if str[-1:] != " ":#处理一种特殊情况:如果字符末尾无空格设置切片无范围结束符号 m = None break elif str[m-1:m]== " ":#结尾有空格,就依次往前推,直到没有空格的位置 m = m - 1 else: break
#print(n) #print(m) return str[n:m]
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('测试成功!')
Sign in to make a reply
Gino_wang
def trim(str): n = 0 m = -1 while n < len(str): if str[n:n+1] == " ": n = n + 1 else: break while abs(m)<len(str): if str[-1:] != " ":#处理一种特殊情况:如果字符末尾无空格设置切片无范围结束符号 m = None break elif str[m-1:m]== " ":#结尾有空格,就依次往前推,直到没有空格的位置 m = m - 1 else: break
测试:
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('测试成功!')