I am getting the below error when I check this function. I am very close, but not understanding why the loop continues after reaching the end of the text. How do I get it to stop searching for the substring after it has reached the end of the string to search?
Error: The call findall('how now brown cow', 'ow') returns (1, 5, 10, 15, -1, 1, 5, 10, 15, -1, 1, 5, 10, 15, -1, 1, 5), not (1, 5, 10, 15).
Note - I have searched through the similar problems here in stack overflow, but do not see anything that is helping me resolve this using the method I have prepared so far. Please advise. Greatly appreciated for this newbie!! :)
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
https://stackoverflow.com/questions/67237702/python-find-a-substring-in-string-and-record-position-of-substrings-in-a-tuple April 24, 2021 at 06:55AM
没有评论:
发表评论