-3

Why does the following program return 1 instead of 2 in python?

print "abcdcdc".count("cdc")

The substring cdc appears in two places(one starting at index 2 and the another starting at index 4). How exactly does the count() work?

Andy
  • 49,085
  • 60
  • 166
  • 233
abysmalpro
  • 45
  • 8

4 Answers4

2

May I refere you to

https://docs.python.org/3.4/library/stdtypes.html?highlight=count#str.count

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.

Community
  • 1
  • 1
Gab
  • 5,604
  • 6
  • 36
  • 52
2

count only returns 1 because the value cdc overlaps itself.

abcdcdc
  |-|
    |-|

To get a value of 2, you need two non-overlapping instances of cdc or utilize a regex:

import re
len(re.findall('(?=cdc)', 'abcdcdc'))
Andy
  • 49,085
  • 60
  • 166
  • 233
1

If you would like to count the total number of occurrences with overlap, you can do this with re module:

import re
text = 'abcdcdc'
len(re.findall('(?=cdc)', text))
>>> 2
Gab
  • 5,604
  • 6
  • 36
  • 52
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
0

Because count() returns the number of non-overlapping occurrences of substring. See Docs.

Psytho
  • 3,313
  • 2
  • 19
  • 27