python-tutorial-Python-courses-python-exercises

Exercise 56

Write a python program as a function which takes as parameter a tuple of string (s, s1) and which returns the index of the first occurrence of s1 found within the string s. The function must returns -1 if s1 is not found within the string s. Example if s = "Python Programming" and s1 = "thon" , the function returns the index 2

Solution

def Find(s , s1):
n = len(s)
m = len(s1)
k = -1
for i in range(0 , n):
if s[i:i+m] == s1:
k = i
break
return k

s = "Python Programming"
s1 = "thon"
print(Find(s , s1)) # display 2
print(Find(s , 'thons')) # display -1

Younes Derfoufi
my-courses.net

Leave a Reply