Python Find All Substrings in a String
In Python, we can use the string'sfind()method or regular expressions to find all substrings in a string. Below is an example usingfind()method's example code:
Example
def find_all_substrings(main_string, sub_string):
start = 0
positions = []
while True:
start = main_string.find(sub_string, start)
if start == -1:
break
positions.append(start)
start += 1
return positions
main_string = "hello world, hello python, hello programming"
sub_string = "hello"
positions = find_all_substrings(main_string, sub_string)
print(positions)
start = 0
positions = []
while True:
start = main_string.find(sub_string, start)
if start == -1:
break
positions.append(start)
start += 1
return positions
main_string = "hello world, hello python, hello programming"
sub_string = "hello"
positions = find_all_substrings(main_string, sub_string)
print(positions)
Code Explanation:
find_all_substringsThe function takes two parameters:main_stringis the main string,sub_stringis the substring to be searched for.startThe variable is used to record the starting position of the search, with an initial value of 0.positionsThe list is used to store the starting positions of all found substrings.while TrueThe loop continues untilfind()the method returns -1, indicating no more substrings are found.main_string.find(sub_string, start)fromstartposition to search for substringsub_string, returns the starting position of the substring. If not found, returns -1.- If a substring is found, add its starting position to the
positionslist, andstartincrease by 1 to continue searching for the next substring. - Finally, return the
positionslist, which contains the starting positions of all substrings.
Output:
[0, 13, 26]
In this example, the substring"hello"appears three times in the main string, at starting positions 0, 13, and 26.
Python3 Examples