我已经提出了这段代码来计算字符串中的多个子字符串。我需要它以元组的形式返回结果。有什么建议吗?
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")
这段代码打印出来: 五 15
我想要它返回: (5,15)
答案 0 :(得分: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)