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