首页 > 解决方案 > Python - 在字符串中查找子字符串并记录元组中子字符串的位置

问题描述

检查此功能时出现以下错误。我非常接近,但不明白为什么循环在到达文本末尾后继续。如何让它在到达要搜索的字符串末尾后停止搜索子字符串?

错误:调用 findall('how now brown cow', 'ow') 返回 (1, 5, 10, 15, -1, 1, 5, 10, 15, -1, 1, 5, 10, 15, - 1, 1, 5),而不是 (1, 5, 10, 15)。

注意 - 我已经在堆栈溢出中搜索了类似的问题,但没有看到任何可以帮助我使用我迄今为止准备的方法解决这个问题的东西。请指教。非常感谢这个新手!!:)

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
    """
    result = ()
    x = 0
    pos = 0
    
    for x in range(len(text)):
        if sub in text:    
            # find pos of sub in text starting from pos in text
            pos = introcs.find_str(text,sub,pos)
            # record result
            result = result + (pos,)
            # increase accumulator by 1 to find next pos of sub in text
            pos = pos + 1
        else:
            # when sub is not present in text
            result = ()     

    return result

标签: python

解决方案


使用递归

def findall(text,sub,list1=[],l=0):
    try:
        a = text.index(sub)
    except:
        return list1
    list1.append(a+l)
    l+=1+a
    return findall(text[a+1:], sub, list1,l)



text = 'aascfvbscaaasc'
sub = 'a'
b=findall(text,sub)
print(text)
print(b)
# [0, 1, 9, 10, 11]

推荐阅读