'Find the second occurrence (index) of substring without overlapping in Python
I need to find the second occurrence of a substring. If there is no second (or first) occurrence, the program should print out a message accordingly.
The occurrences cannot overlap. For example, in the string "aaaa" the second occurrence of the substring "aa" is at index 2.
I'm new to python and any help will be appreciated. Below is my code.
string=input("Please type in a string:")
substring=input("Please type in a substring:")
index=string.find(substring,string.find(substring)+1)
if index != -1 :
print(f"The second occurrence of the substring is at index {index}.")
else:
print("The substring does not occur twice in the string.")
The current code gives the output index as 1 instead of 2
Solution 1:[1]
You need to change the start index of the find() method. When you get a string, you want to find the index of the character after the first occurence, so get get the index the first character of the first occurence with the find() method and add the length of the searched word.
searched = "Mike"
sentence = "Hey ! Mike is with Mike"
sentence.find(searched) # 6
Here, the find() method returns 6 (the index of the first char of the searched word), so you add the length of the searched word (5) and you get 11. Finally, you get this result :
string = input("Please type in a string:")
substring = input("Please type in a substring:")
index = string.find(substring, string.find(substring) + len(substring))
if index != -1 :
print(f"The second occurrence of the substring is at index {index}.")
else:
print("The substring does not occur twice in the string.")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukas Laudrain |
