Python Find All Substrings in a String

Document 对象参考手册Python3 Examples

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)

Code Explanation:

  1. find_all_substringsThe function takes two parameters:main_stringis the main string,sub_stringis the substring to be searched for.
  2. startThe variable is used to record the starting position of the search, with an initial value of 0.
  3. positionsThe list is used to store the starting positions of all found substrings.
  4. while TrueThe loop continues untilfind()the method returns -1, indicating no more substrings are found.
  5. main_string.find(sub_string, start)fromstartposition to search for substringsub_string, returns the starting position of the substring. If not found, returns -1.
  6. If a substring is found, add its starting position to thepositionslist, andstartincrease by 1 to continue searching for the next substring.
  7. Finally, return thepositionslist, 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.

Document 对象参考手册Python3 Examples

Other Extensions