-1

I am provided a string and a substring in python. I have to check how many times the substring appears in the string. My input is the string and substring. My output should be the number of appearances.

Input:

string: ABCDCDC

substring: CDC

Output: 2

Here's what I did:

def count_substring(string, sub_string):
    string_length = len(string)
    for i in range(0, string_length):
        print(string[i], end="")

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

The Output:

ABCDCDCNone

I also tried to use the .count function but it only sees one appearance of the sub_string and not 2.

It got me the text but I don't know how to continue from here.

  • In particular, look at the answers below the top one, which deal with overlapping substrings. – Kaia Jan 16 '23 at 03:10

1 Answers1

0

One approach uses regex with a positive lookahead (?=CDC):

import re

inp = "ABCDCDC"
count = len(re.findall(r'(?=CDC)', inp))
print(count)  # 2

This regex trick works correctly even with overlapping substrings. This is because positive lookaheads match but do not consume.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360