Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python finding all substrings in a string

Python finding all substrings in a string

Document Object Reference Manual Python3 Examples

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

)

print

(

positions

)

Code analysis:

  1. find_all_substrings The function accepts two parameters:main_string is the main string,sub_string is the substring to find.
  2. start variable is used to record the starting position of the search, initialized to 0.
  3. positions list is used to store the starting positions of all found substrings.
  4. while True The loop continues until find() method returns -1, indicating no more substrings were found.
  5. main_string.find(sub_string, start) From the start position to find the substring sub_string, returning the starting position of the substring. If not found, returns -1.
  6. If the substring is found, add its starting position to positions list, and increment start by 1 to continue searching for the next substring.
  7. Finally, return positions list, 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.

Document Object Reference Manual Python3 Examples