How to find index method using loop. not with inbuilt method

Viewed 901

How to implement index method using loop.

sub_str is found in my_str then it will print the index of first occurrence of first character of matching string in my_str.

Input:

my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.',
sub_str = 'Pickl'

Output

29

Code is below

main="Peter Piper Picked A Peck Of Pickled Peppers"
sub="Pickl"
t = main.split()
for i in range (0,len(t)):
    match = True
    if sub in t[i]:
        print(i)

My output is 6

Expected Out is 29

4 Answers

I think you want the start index of the substring in the input string (which would be 29). The splt() method defaults to splitting a string where there are spaces; into words, not individual letters. That is why you get an output of 6.

You can find the start index of a substring with the find() method:

output = main.find(sub)

You should use 2 nested loops

def myindex(main,sub):
    for kk in range (len(main) - len(sub)):
        match = True
        for ii in range(len(sub)):
            if main[kk+ii] != sub[ii]:
                match = False
                break
        if match:
            return kk
    return -1

>>> myindex("Peter Piper Picked A Peck Of Pickled Peppers","Pickl")
29

6 is the index of an element that matches with your substring in the array after splitting the array into chunks of words if you want to find the index of the substring you can use the find() method in your case it would be:

main="Peter Piper Picked A Peck Of Pickled Peppers"
sub="Pickl"
t = main.find(sub)
print(t)

Here t will be 29

what you can do is:

my_str = "Peter Piper Picked A Peck Of Pickled Peppers."
sub_str = "Pickl"

for i in range(0,len(my_str)):
    if my_str[i:i+len(sub_str)] == sub_str:
        print(i)

I haven't tried it yet so it might need some tweakings.

Related