Python finding all substrings in a string
In Python, we can use the string's find() method or regular expressions to find all substrings in a string. Below is an example using find() method:
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
)
(
positions
)
Code analysis:
find_all_substringsThe function accepts two parameters:main_stringis the main string,sub_stringis the substring to find.startvariable is used to record the starting position of the search, initialized to 0.positionslist is used to store the starting positions of all found substrings.while TrueThe loop continues untilfind()method returns -1, indicating no more substrings were found.main_string.find(sub_string, start)From thestartposition to find the substringsub_string, returning the starting position of the substring. If not found, returns -1.- If the substring is found, add its starting position to
positionslist, and incrementstartby 1 to continue searching for the next substring. - Finally, return
positionslist, which contains the starting positions of all substrings.
Output result:
[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