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
Release: 2024-12-09 17:08:18
Original
848 people have browsed it

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template