python - I need this Substring counting program to return a Tuple -
i have come piece of code count multiple substrings within string. need return results in tuple. suggestions?
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")
this piece of code prints: 5 15
i return: (5,15)
try this:
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)
even better, can simplify whole function this:
from re import finditer def findsubstringmatch(target, key): return tuple(m.start() m in finditer(key, target))
either way, works expected:
findsubstringmatch("atgacatgcacaagtatgcat", "atgc") => (5, 15)
Comments
Post a Comment