Как найти количество подстрок в строке python

Given a string and a substring, write a Python program to find how many numbers of substrings are there in the string (including overlapping cases). Let’s discuss a few methods below.

Method #1: Using re.findall() Method

Python3

import re

s = 'ababababa'

res= len(re.findall('(?=(aba))', s))

print("Number of substrings", res)

Output

Number of substrings 4

  Method #2: Using startswith() 

Python3

ini_str = "ababababa"

sub_str = 'aba'

res = sum(1 for i in range(len(ini_str))

        if ini_str.startswith("aba", i))

print("Number of substrings", res)

Output:

Number of substrings 4

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #3: Using count() Method

Python3

ini_str = "ababababa"

sub_str = 'aba'

def Countofoccurrences(ini_str,sub_str):

    count = 0

    start = 0

    while start < len(ini_str):

        pos = ini_str.find(sub_str, start)

        if pos != -1:

            start = pos + 1

            count += 1

        else:

            break

    return count

print("Number of substrings", Countofoccurrences(ini_str,sub_str))

Output

Number of substrings 4

Method #4: Using List Comprehension

In this method, we are using a list comprehension to check if the substring is present in the main string or not. We are using the range of length of the main string minus the length of the substring plus 1. We are then checking if the substring present in the main string at the current index is equal to the given substring or not and incrementing the count accordingly.

Python3

ini_str = "ababababa"

sub_str = 'aba'

res = sum([1 for i in range(len(ini_str)-len(sub_str)+1) if ini_str[i:i+len(sub_str)] == sub_str])

print("Number of substrings", res)

Output

Number of substrings 4

Time Complexity: O(n)
Auxiliary Space: O(1)

Approach#4: Using sliding window

This program uses a sliding window technique to slide a window of size m over the input string ini_str. At each step, it checks if the substring in the window is equal to sub_str, and if it is, it increments the count variable. It slides the window by iterating over the indices of the input string from 0 to n – m + 1.

Algorithm

1. Initialize count variable to 0
2. Find length of the input string ini_str and length of the substring to be counted sub_str
3. Iterate over the indices of the input string from 0 to n – m + 1
4. At each index, extract a substring of length m from ini_str
5. Compare the extracted substring with the sub_str, if it matches, increment the count variable
6. Return the count variable

Python3

ini_str = "ababababa"

sub_str = 'aba'

count = 0

n = len(ini_str)

m = len(sub_str)

for i in range(n - m + 1):

    if ini_str[i:i+m] == sub_str:

        count += 1

print("Number of substrings:", count)

Output

Number of substrings: 4

Time complexity: O(n * m), where n is the length of the input string and m is the length of the substring to be counted. This is because the program iterates over the input string ini_str n – m + 1 times, and at each step, it extracts a substring of length m and compares it with sub_str.

Space complexity: O(1), as it only uses a constant amount of additional space to store the count variable, the length of the input string n, and the length of the substring to be counted m. It does not create any new data structures or use any additional memory proportional to the size of the input.

Last Updated :
19 Apr, 2023

Like Article

Save Article

The current best answer involving method count doesn’t really count for overlapping occurrences and doesn’t care about empty sub-strings as well.
For example:

>>> a = 'caatatab'
>>> b = 'ata'
>>> print(a.count(b)) #overlapping
1
>>>print(a.count('')) #empty string
9

The first answer should be 2 not 1, if we consider the overlapping substrings.
As for the second answer it’s better if an empty sub-string returns 0 as the asnwer.

The following code takes care of these things.

def num_of_patterns(astr,pattern):
    astr, pattern = astr.strip(), pattern.strip()
    if pattern == '': return 0

    ind, count, start_flag = 0,0,0
    while True:
        try:
            if start_flag == 0:
                ind = astr.index(pattern)
                start_flag = 1
            else:
                ind += 1 + astr[ind+1:].index(pattern)
            count += 1
        except:
            break
    return count

Now when we run it:

>>>num_of_patterns('caatatab', 'ata') #overlapping
2
>>>num_of_patterns('caatatab', '') #empty string
0
>>>num_of_patterns('abcdabcva','ab') #normal
2

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Python String count() function is an inbuilt function in Python programming language that returns the number of occurrences of a substring in the given string.

    Python String count() Method Syntax

    Syntax: string.count(substring, start=…, end=…)

    Parameters: 

    • The count() function has one compulsory and two optional parameters. 
      • Mandatory parameter: 
        • substring – string whose count is to be found.
      • Optional Parameters: 
        • start (Optional) – starting index within the string where the search starts. 
        • end (Optional) – ending index within the string where the search ends.

    Return Value: count() method returns an integer that denotes number of times a substring occurs in a given string. 

    String count() method in Python Examples

    Let us see a few examples of the String count() method in Python.

    Count Number of Occurrences of a given Substring

    In this example, we will pass only one argument which is mandatory, and skip the optional arguments.

    Python3

    string = "geeks for geeks"

    print(string.count("geeks"))

    Output: 

    2

    Time Complexity: O(n), where n is the length of the string. This is because we need to traverse the entire string to count the occurrence of the substring.
    Auxiliary Space: O(1), as we are not using any extra space in the program, only a string variable is used to store the input string.

    String count() Method using Start and End Parameter

    In this example, we will pass all three arguments to find the occurrence of a substring in a Python String.

    Python3

    string = "geeks for geeks"

    print(string.count("geeks", 0, 5))

    print(string.count("geeks", 0, 15))

    Output: 

    1
    2

    Last Updated :
    09 May, 2023

    Like Article

    Save Article

    Посчитывает количество вхождений символа/подстроки в строку.

    Синтаксис:

    str.count(sub[, start[, end]])
    

    Параметры:

    • substr, строка или символ;
    • startint, индекс начала поиска, по умолчанию 0, необязательно;
    • endint, конец, индекс конца поиска, по умолчанию len(str), необязательно.

    Возвращаемое значение:

    • int, количество вхождений подстроки sub.

    Описание:

    Метод str.count() возвращает количество вхождений подстроки sub в строку str в диапазоне индексов [start, end], если они переданы в метод.

    • Необязательные аргументы start и end интерпретируются как обозначения среза строки.
    • При вызове без аргументов бросает исключение TypeError (требуется как минимум1аргумент, передано0`).

    Примеры подсчета количества символов/подстрок в строке.

    >>> x = 'количество вхождений подстроки `sub` в диапазоне индексов'
    
    >>> x.count('и')
    # 5
    
    >>> x.count('и', 6)
    # 4
    
    >>> x.count('о', 10, 30)
    # 3
    
    >>> x.count('`')
    # 2
    
    >>> x.count('вхождений')
    # 1
    
    # Без параметров
    >>> x.count()
    # Traceback (most recent call last):
    #   File "<stdin>", line 1, in <module>
    # TypeError: count() takes at least 1 argument (0 given)
    

    Время чтения 2 мин.

    count() — это встроенная в Python функция, которая возвращает вам количество заданного элемента в списке или строке.

    Функция Python String count()

    Содержание

    1. Python string count()
    2. Синтаксис
    3. Параметры
    4. Возвращаемое значение
    5. Использование параметров Start и End

    Python string count() — это встроенная функция, которая возвращает количество вхождений подстроки в данной строке. Метод count() ищет подстроку в заданной строке и возвращает, сколько раз эта подстрока присутствует в ней. Он также принимает необязательные параметры start и end, чтобы указать начальную и конечную позиции в строке соответственно.

    Синтаксис

    Синтаксис Python string count() следующий:

    string.count(substring, start, end)

    Параметры

    Функция count() имеет один обязательный и два необязательных параметра.

    1. substring является обязательным параметром, представляющим собой строку, количество которой необходимо найти.
    2. Необязательный параметр start является начальным индексом в строке, с которой начинается поиск.
    3. Параметр end также необязателен и является конечным индексом в строке, где заканчивается поиск.

    Возвращаемое значение

    Метод Python String count() возвращает целое число, обозначающее, сколько раз подстрока встречается в данной строке.

    См. следующий пример.

    # app.py

    friend = ‘What did you bring Mr. Bing’

    substring = ‘ing’

    count = friend.count(substring)

    print(‘The substring occurs {} times’.format(count))

    Здесь мы использовали ing как подстроку и проверяем, сколько раз она повторяется внутри строки. Кроме того, мы использовали формат строки для форматирования строки.

    См. следующий вывод.

    Пример подсчета строк Python

    Использование параметров Start и End

    Давайте возьмем пример, где мы передаем параметры start и end.

    # app.py

    friend = ‘What did you bring Mr. Bing’

    substring = ‘ing’

    count = friend.count(substring, 11, 18)

    print(‘The substring occurs {} times’.format(count))

    См. вывод приведенного выше примера.

    Используйте параметр «Начало и конец»

    Он будет подсчитывать количество подстрок между 11-м и 18-м символами индекса. В нашем примере ing встречается только однажды между этими символами, поэтому мы видим его один раз.

    Функция Python count() во встроенной функции языка программирования Python, которая возвращает количество вхождений подстроки в предоставленной строке.

    Понравилась статья? Поделить с друзьями:
  • Как найти ватсап веб на айфоне
  • Как найти гражданско правовой договор
  • Как исправить впадины на бедрах
  • Как составить квест по литературе
  • Как составить меню при грудном вскармливании