Discuss / Python / python切片作业:独立思考了2个钟头,-_-||

python切片作业:独立思考了2个钟头,-_-||

Topic source

Gino_wang

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

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


  • 1

Reply