Home >Backend Development >Python Tutorial >How Can I Count Substring Occurrences in Python, Including Overlapping Cases?

How Can I Count Substring Occurrences in Python, Including Overlapping Cases?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 17:08:18846browse

How Can I Count Substring Occurrences in Python, Including Overlapping Cases?

Finding Substring Occurrences in a String

Determining the frequency of a substring within a string is a fundamental task in many programming scenarios. Python offers a convenient method to count substrings within a given text.

Counting Non-Overlapping Occurrences

For non-overlapping occurrences, Python provides the count() method. This method takes the substring as an argument and returns the number of times it appears in the string.

For instance:

>>> 'foo bar foo'.count('foo')
2

Counting Overlapping Occurrences

If you need to count overlapping occurrences, the count() method is not directly applicable. You can employ a more direct approach by iterating through the string and checking for the substring at each position. This method provides accurate results for overlapping occurrences.

For example:

def count_overlapping(string, substring):
    count = 0
    for i in range(len(string)):
        if string[i:i + len(substring)] == substring:
            count += 1
    return count

>>> count_overlapping('abcdabcva', 'ab')
3

The above is the detailed content of How Can I Count Substring Occurrences in Python, Including Overlapping Cases?. 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