-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
  • 46,308
  • 56
  • 161
  • 219
abysmalpro
  • 35
  • 7

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,156
  • 6
  • 35
  • 51
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
  • 46,308
  • 56
  • 161
  • 219
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,156
  • 6
  • 35
  • 51
Sebastian Wozny
  • 14,490
  • 5
  • 45
  • 61
0

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

Psytho
  • 3,025
  • 1
  • 17
  • 25