Find All Occurrences of a Substring in a String in Python
import re # defining string str1 = "This dress looks good; you have good taste in clothes." #defining substring substr = "good" print("The original string is: " + str1) print("The substring to find: " + substr) result = [_.start() for _ in re.finditer(substr, str1)] print("The start indices of the substrings are : " + str(result)) # Output - # The original string is: This dress looks good; you have good taste in clothes. # The substring to find: good # The start indices of the substrings are : [17, 34]
Here is what the above code is Doing:
1. We have defined a string str1 and a substring substr.
2. We have used the re.finditer() method to find all the indices of the substring in the string.
3. We have used a list comprehension to extract the start indices of the substrings.
4. We have printed the result.