Python | All occurrences of substring in string

Python | All occurrences of substring in string

If you want to find all occurrences of a substring in a string and get their indices in Python, you can use the following methods:

  1. Using a loop and str.find():

    The find() method returns the lowest index of the substring (if found). If not found, it returns -1.

    def find_all_occurrences(main_string, substring): start = 0 while start < len(main_string): start = main_string.find(substring, start) if start == -1: break yield start start += 1 string = "hello world, hello universe" substring = "hello" print(list(find_all_occurrences(string, substring))) 
  2. Using Regular Expressions:

    This method is especially useful when searching for patterns in the string.

    import re def find_all_occurrences(main_string, substring): return [match.start() for match in re.finditer(substring, main_string)] string = "hello world, hello universe" substring = "hello" print(find_all_occurrences(string, substring)) 

Both methods will output:

[0, 13] 

This indicates that the substring "hello" is found at index 0 and 13 in the main string.


More Tags

jacoco predicate adapter ta-lib session timepicker esp8266 apache-nifi masked-array android-json

More Programming Guides

Other Guides

More Programming Examples