首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在我的代码中寻找漏洞(split方法)

在我的代码中寻找漏洞(split方法)
EN

Stack Overflow用户
提问于 2020-08-25 22:17:42
回答 1查看 81关注 0票数 0

在这里,我尝试在Python中重新创建str.split()方法。我已经尝试并测试了这段代码,它工作得很好,但我正在寻找要纠正的漏洞。一定要检查一下,如果有反馈的话,给出反馈。编辑:很抱歉说得不够清楚,我的意思是在代码不能工作的情况下请求你们的例外。我也在试着想一种更好的方式,而不是看源代码。

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

发布于 2020-08-25 22:36:57

实际上,您的代码存在一些问题:

  • 通过从x+1搜索,您可能会错过在字符串的最开始处出现split_by,从而导致index在最后一次迭代中失败。只有在分隔符是空格的情况下,才能比
  • 更频繁地调用index,并且即使这样也可能删除更多的内容,例如,在拆分lines
  • instead,时将len(split_by)添加到下一次调用的偏移量中需要在最后一步中两次反转字符串

这应该可以解决这些问题:

代码语言:javascript
运行
复制
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 output
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63580865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档