Home >Backend Development >Python Tutorial >How Can I Find All Occurrences of a Substring in a Python String?

How Can I Find All Occurrences of a Substring in a Python String?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 00:53:38855browse

How Can I Find All Occurrences of a Substring in a Python String?

Finding All Occurrences of a Substring

Python provides extensive string manipulation capabilities, including the functions string.find() and string.rfind() which retrieve the first occurrence of a substring from the beginning and end, respectively. However, these functions fall short when we seek to find all occurrences of a substring.

Solution: Harnessing Regular Expressions

In the absence of a built-in "string.find_all()" function, we can leverage the power of regular expressions:

import re

text = "test test test test"

# Find all occurrences of "test"
matches = [m.start() for m in re.finditer('test', text)]

# Print the found indexes
print(matches)  # [0, 5, 10, 15]

This solution iterates over the result of re.finditer('test', text), a generator that yields match objects for each discovered occurrence. By extracting the start() property from each match, we obtain a list of indexes representing the position of the substring in the original string.

Handling Overlapping Matches

If overlapping matches are permitted, they can be captured by employing lookahead assertions in the regular expression:

matches = [m.start() for m in re.finditer('(?=tt)', 'ttt')]
# [0, 1]

Performing Reverse Searches

To perform a reverse find-all without overlaps, a combination of positive and negative lookahead can be used:

search = 'tt'
matches = [m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
# [1]

By utilizing regular expressions, we can effectively identify and retrieve all occurrences of a substring in a Python string.

The above is the detailed content of How Can I Find All Occurrences of a Substring in a Python String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn