The first chunk is what I thought would append a list with the positions of all matching instances of a substring in a larger string. I am applying this to importing a txt file but for the sake troubleshooting I just created importTxt.
def blahTxt():
importTxt = ['blhaahblhaahhablahblahlahblahlablhaahlalablahahblahblha', 'blah']
return importTxt
def main():
myList = []
s = blahTxt()[0]
t = blahTxt()[1]
for i in range(len(s)):
if s[i:i] == t:
myList.append(i)
print(myList)
main()
The above code will not return the locations, it just prints []
.
def blahTxt():
importTxt = ['blhaahblhaahhablahblahlahblahlablhaahlalablahahblahblha', 'blah']
return importTxt
def main():
myList = []
s = blahTxt()[0]
t = blahTxt()[1]
for i in range(len(s) - len(t)): # added - length of t
if s[i:i + len(t)] == t: # added + length of t
myList.append(i)
print(myList)
main()
When I run this program myList contains all of the locations of t in s. I added the -len(t) and +len(t) to the program however I couldn't figure out why this works. Why do I need to add - len(t) to the range and add + len(t) to the if statement for this program to work?