Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Find string appears s2 in s1

s1 = 'timisverytimidbuthasnotime'
s2 = 'tim'
Write a python function to find out no. of times the string s2 appears in string s1 ? without inbuilt function
by

1 Answer

iamabhishek
Try this:

def count_occurrences(s1, s2):
count = 0
for i in range(len(s1) - len(s2) + 1):
if s1[i:i+len(s2)] == s2:
count += 1
return count

s1 = 'timisverytimidbuthasnotime'
s2 = 'tim'
print(count_occurrences(s1, s2)) # Output will be 2

Login / Signup to Answer the Question.