In Python, can you find a substring using a for loop and equivalence (==) ? No regex

Viewed 5018

Here is my problem: Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack. I am encouraged to use a loop and the equivalence operator.

I'm not making much progress - here is my code after 4 hours...

..after two days I've got this...

needle = 'sses'
haystack = 'assesses'
count = 0                  # initialize the counter
index = haystack.index(needle) # get the first character in the substring
string1 = haystack[index:len(needle) + index] # get the whole substring

for position in range(0,len(haystack)): # loop through the string
    if haystack[position:len(needle) + index] == string1: # match the 1st substring
    count += 1 # iterate the counter
print (count)

...my problem is, how do I get the for loop to count the second occurance of the string?

Thanks

Tim

Finally, the 'correct' answer:

needle = input()
haystack = input()
count = 0
if needle in haystack:
    index = haystack.index(needle)
    string1 = haystack[index:len(needle) + index]
    for position in range(0,len(haystack)):
        if haystack[position:len(needle) + position] == string1:
            count += 1
 print (count)
1 Answers
Related