1

In the code, count()-ing "CD" gives the correct answer (2) but for count()ing "CDC" it only gives 1. Why?

And how to count "CDC" ?

v="ABCDCDC"
print(v.count("CD"))  #2
print(v.count("CDC")) #1
output
2
1

This works, but is there any simple string method to use?

def count_substring(string, sub_string):
    #return(string.count(sub_string))
    #return
    n=len(string)
    m=len(sub_string)
    sum=0
    for i in range(n-m+1):
        a=i+m
        if string[i:a]==sub_string:
            sum=sum+1
    return(sum)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
sreekar kaja
  • 31
  • 1
  • 3
  • It doesn't count overlapping matches. – Barmar Oct 24 '19 at 17:56
  • 1
    "Why was the function designed this way?" is an interesting question, but it's going to be hard to answer, since there's no justification given in the documentation or (AFAICT) the source code. – Kevin Oct 24 '19 at 18:01

1 Answers1

2

The documentation here states that count does not count overlapping matches:

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

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

iz_
  • 15,923
  • 3
  • 25
  • 40
  • While this answers the _why_, here are the answers to _how can I do it instead_: [String count with overlapping occurrences](https://stackoverflow.com/q/2970520/2745495) – Gino Mempin Nov 09 '22 at 04:39