To find the indices of all occurrences of a substring in Python, you can use the finditer method of the re module in a loop to find all occurrences and store their indices.
In this example,
re
module.str
with a string value.finditer
method of the re
module with a regular expression pattern to find all occurrences of the pattern within str
and store their indices.import re
str = 'Hello Hello Hello'
pattern = re.compile('Hello')
matches = pattern.finditer(str)
indices = [match.start() for match in matches]
print('Indices of all occurrences:', indices)
Indices of all occurrences: [0, 6, 12]
In this example,
re
module.str1
and str2
with different values.finditer
method of the re
module with a regular expression pattern to find all occurrences of the pattern within str1
and store their indices.import re
str1 = 'apple banana cherry banana'
str2 = 'banana'
pattern = re.compile(str2)
matches = pattern.finditer(str1)
indices = [match.start() for match in matches]
print('Indices of all occurrences:', indices)
Indices of all occurrences: [6, 20]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Python language with well detailed examples.