简体   繁体   中英

How to find all occurences of substring in string, in python

I need help explaining how this solution I found on stack overflow works. Why if k = -1, do you need to return positions. If I change it to return anything else, it does not work. Thank you.

def findSubstring(sequence, substring):
    positions = []
    k = 0
    while k < len(sequence):
        k = sequence.find(substring, k)
    if k == -1:
        return positions
    else:
        positions.append(k)
        k += 1 #change to k += len(sub) to not search overlapping results
print(positions)

str.find() returns the index of the first occurrence of the substring (if found). If not found, it returns -1.

This is what happens in the findSubstring function:

  • First, an empty list is created to later add the indexes of occurrence of the substring.

  • while k < len(sequence) : we want to look for the substring until we get to the last index of the sequence.

  • k = sequence.find(substring, k) : we assgin the index of the first occurrence of the substring after index k (which for the first iteration should be the beginning of the sequence and that's the reason for setting k=0 before the while statement.)

  • Now, if the substring wasn't in the sequence k=-1 and else the index which the substring occurred.

  • if k == -1: return(positions) : if the substring isn't found, k=-1 and the empty positions list is returned, otherwise the index, k, is appended to the positions and the k +=1 will make sure that in the next iteration, we look for the substring starting after the index tha was just found.

  • we iterate over k until we get to the end of the sequence ( while k len(sequence) )

  • print(positions) : the function returns the list of indexes and we print it in the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM