1

我想出了这段代码来计算字符串中的多个子字符串。我需要它以元组的形式返回结果。有什么建议么?

def FindSubstringMatch(target, key):
    PositionList = 0
    while PositionList < len(target):
        PositionList = target.find(key, PositionList)
        if PositionList == -1:
            break
        print(PositionList)
        PositionList += 2

FindSubstringMatch("atgacatgcacaagtatgcat", "atgc")

这段代码打印:5 15

我希望它返回:(5,15)

4

1 回答 1

2

尝试这个:

def FindSubstringMatch(target, key):
    PositionList = 0
    result = []
    while PositionList < len(target):
        PositionList = target.find(key, PositionList)
        if PositionList == -1:
            break
        result.append(PositionList)
        PositionList += 2
    return tuple(result)

更好的是,您可以像这样简化整个函数:

from re import finditer

def findSubstringMatch(target, key):
    return tuple(m.start() for m in finditer(key, target))

无论哪种方式,它都按预期工作:

findSubstringMatch("atgacatgcacaagtatgcat", "atgc")
=> (5, 15)
于 2013-08-08T02:45:24.893 回答