我想出了这段代码来计算一个字符串中的多个子字符串。我需要它以元组返回结果。有什么建议么?
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)
最佳答案
尝试这个:
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)