Reputation: 597
I wrote a Python code to find a substring from a string. If the substring is not found in the main string, then it output as "Substring not found" as expected. The issue is when it find the substring the loop runs endlessly.
Below is the code:
mainstr = input("Enter main string: ")
substr = input("Enter substring: ")
flag = False
n=len(a)
while True:
pos = a.find(b,0,n)
if pos == -1:
break
print("Found at index :", pos)
flag = True
if flag == False:
print("Substring not found")
OutPut:
Enter main string: today
Enter substring: day
Found at index : 2
Found at index : 2
Found at index : 2
Found at index : 2
Found at index : 2
Found at index : 2
.
.
.
endless
I made a small change in the line 7, changed "pos = a.find(b,pos+1,n)" instead of "pos = a.find(b,0,n)"
(I found the below code in online tutorial)
mainstr = input("Enter main string: ")
substr = input("Enter substring: ")
flag = False
pos = -1
n=len(a)
while True:
pos = a.find(b,pos+1,n)
if pos == -1:
break
print("Found at index :", pos)
flag = True
if flag == False:
print("Substring not found")
OutPut:
Enter main string: today is civic day
Enter substring: day
Found at index : 2
Found at index : 15
My doubt is initially assigining "0" or "pos+1" for begin in find function meaning same. But why for one condition it runs endlessly and for other condition it outputs as expected? what is the difference between the two: initiall assigining "0" and "pos+1" for begin in find function.
Upvotes: 0
Views: 91
Reputation: 666
The key is in noting the difference between pos = a.find(b,pos+1,n)
and pos = a.find(b,0,n)
.
Your code just checks for just the first substring repeatedly from positions 0 to n everytime. However, the other code, checks for multiple substrings by changing the value of pos each time so that the detected substrings are skipped in the next iteration and the remaining part of the string is checked. So that code exits when no further substrings are found in the remaining string.
TLDR: the value of pos changes in each iteration in the code from the online tutorial.
Upvotes: 1
Reputation: 3419
In the first case, you are searching from 0
index always in the while loop and it always find index 2
as the substring index and the returns the index as a result.
In the second case, you are searching from 0
in the first execution of the loop then you are assigning
pos = a.find(b,pos+1,n)
That will make pos = 2
which is where the substring is found so pos + 1
in the next iteration will be 3
so the search starts from there. And then so on, it reaches the end of the loop and eventually the substring does not exist.
Upvotes: 3