0

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?

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
zostrom
  • 3
  • 2

2 Answers2

0

Add print(repr(s[i:i]), repr(s[i:i + len(t)])) to your code. You'll see the first returns an empty string. That's because slicing is open on the right..., In the general case [a:b] includes the value at position a but not b. It makes sense when you think about it. [0:3] should return 3 things, not 4.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You could picture it like this:

s = 'blhaahblhaahhablahblahl ... ha'
t =               'blah'
#                  ^   ^
#                  |   |
#                s[i : i + len(t)]

The substring of s is specified by s[i : i+len(t)] in a way that works for any length of the sought after string.

And you should read up on slice notation because you are going to use it a lot.

figbeam
  • 7,001
  • 2
  • 12
  • 18