在这里,我尝试在Python中重新创建str.split()方法。我已经尝试并测试了这段代码,它工作得很好,但我正在寻找要纠正的漏洞。一定要检查一下,如果有反馈的话,给出反馈。编辑:很抱歉说得不够清楚,我的意思是在代码不能工作的情况下请求你们的例外。我也在试着想一种更好的方式,而不是看源代码。
def splitt(string,split_by = ' '):
output = []
x = 0
for i in range(string.count(split_by)):
output.append((string[x:string.index(split_by,x+1)]).strip())
x = string.index(split_by,x+1)
output.append((((string[::-1])[:len(string)-x])[::-1]).strip())
return output发布于 2020-08-25 22:36:57
实际上,您的代码存在一些问题:
x+1搜索,您可能会错过在字符串的最开始处出现split_by,从而导致index在最后一次迭代中失败。只有在分隔符是空格的情况下,才能比index,并且即使这样也可能删除更多的内容,例如,在拆分lineslen(split_by)添加到下一次调用的偏移量中需要在最后一步中两次反转字符串这应该可以解决这些问题:
def splitt(string,split_by=' '):
output = []
x = 0
for i in range(string.count(split_by)):
x2 = string.index(split_by, x)
output.append((string[x:x2]))
x = x2 + len(split_by)
output.append(string[x:])
return outputhttps://stackoverflow.com/questions/63580865
复制相似问题