0

I have an exercise that find how many time a sub string appear in a main string.

2 inputs are main string and sub string.

I used string.count() but with the main string "abcdcdc" and sub string "cdc", the result only 1 why you can see the sub string "cdc" appeared twice time "abcdcdc" & "abcdcdc".

So that I would like to know why my code provided incorrect result. Does the string.count() on calculate one time for each apperance? Hereunder is my code:

 strs=str(input())
 sub_str=str(input())

print(strs.count(sub_str))

Thank you very much.

khelwood
  • 55,782
  • 14
  • 81
  • 108
zickk2894
  • 21
  • 4
  • [str.count](https://docs.python.org/3/library/stdtypes.html#str.count) — "Return the number of **non-overlapping** occurrences" – khelwood Mar 18 '19 at 13:55

2 Answers2

0

Please see How String.count() works?

count() only counts non-overlapping substrings.

Clay
  • 64
  • 1
  • 6
0

From the documentation here: str.count

Return the number of non-overlapping occurrences of substring

The two occurrences in your example overlap. The number of non-overlapping occurrences is one.

khelwood
  • 55,782
  • 14
  • 81
  • 108