【问题标题】:Trying to create a While Loop in PYthon to find strings in other strings尝试在 PYthon 中创建一个 While 循环以在其他字符串中查找字符串
【发布时间】:2022-08-19 05:04:54
【问题描述】:

我正在尝试实现此功能。看起来很简单,但我的代码失败了,我不知道为什么。

def findall(text,sub):
    \"\"\"
    Returns the tuple of all positions of substring sub in text.
    
    If sub does not appears anywhere in text, this function returns the empty tuple ().
    
    Examples:
        findall(\'how now brown cow\',\'ow\') returns (1, 5, 10, 15)
        findall(\'how now brown cow\',\'cat\') returns ()
        findall(\'jeeepeeer\',\'ee\') returns (1,2,5,6)
    
    Parameter text: The text to search
    Precondition: text is a string
    
    Parameter sub: The substring to search for
    Precondition: sub is a nonempty string
    \"\"\"
    import introcs
    result= ()
    pos=0

    while pos < len(text):
        x=text[pos:pos+2]
        if x is sub:
            result=result+(x, )
            pos+1
        else:
            result=result
            pos+1
    
    return result

    标签: python loops


    【解决方案1】:

    当前代码中有几个问题。以下是最低限度的更正,并附有一些建议(在评论中)。

    def findall(text,sub):
        result= ()
        pos=0
    
        while pos < len(text):
            x=text[pos:pos+len(sub)]  # use len(sub) instead of 2
            if x == sub:              # use == instead of is
                result=result+(pos, ) # store pos, not x
                pos = pos+1           # assign RHS to pos
            else:
                result=result
                pos = pos+1           # assign RHS to pos
    
        return result
    
    print(findall('how now brown cow','ow')) # (1, 5, 10, 15)
    print(findall('how now brown cow','cat')) # ()
    print(findall('jeeepeeer','ee')) # (1, 2, 5, 6)
    

    特别是,is 检查两个对象是否是同一个实体。要按内容比较字符串,一般应使用==

    改用生成器表达式:

    def findall(text,sub):
        return tuple(i for i in range(len(text)) if text[i:i+len(sub)] == sub)
    

    【讨论】:

    • 哦,伙计,非常感谢你!我从像你这样善良的人那里学到的东西比从我的教授那里学到的更多。谢谢您的帮助!
    猜你喜欢
    • 2013-07-16
    • 2017-03-29
    • 1970-01-01
    • 2015-06-26
    • 2015-01-02
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    相关资源
    最近更新 更多