-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.

1
  • In particular, look at the answers below the top one, which deal with overlapping substrings. Commented Jan 16, 2023 at 3:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.