I was trying to understand the functioning of string.count basically The documented definition of it is
string.count(s, sub[, start[, end]])
Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.
Now what's the exact meaning of last line here which is bold actually. I did some random experiment with this function
In [19]: a
Out[19]: 'ab'
In [23]: string.count(a,'ab'[1:3])
Out[23]: 1
In [24]: string.count(a,'ab'[1:1])
Out[24]: 3
In [25]: string.count(a,'ab'[-1:1])
Out[25]: 3
In [26]: string.count(a,'ab'[-1:0])
Out[26]: 3
In [27]: string.count(a,'ab'[1:4])
Out[27]: 1
In [28]: string.count(a,'ab'[1:100])
Out[28]: 1
In [29]: string.count(a,'ab'[100:100])
Out[29]: 3
In [30]: string.count(a,'ab'[:])
Out[30]: 1
In [31]: string.count(a,'a'[:])
Out[31]: 1
Can anybody explain me why some times I am getting result as 1 and why sometimes 3 here. Overall I need to understand how this function works exactly ?
Everytime you see a 3
as result, the second parameter was the empty string – you hide this facte by using strange slicings. The empty string is considered to occur at the positions 0:0
, 1:1
and 2:2
for this example, so there are three occurrences. In general, string.count(s, "")
(or equivalently, s.count("")
) will return len(s) + 1
.
To explain how this result comes about, here is a (not very efficient) example implementation of string.count()
:
def count(s, sub):
result = 0
for i in range(len(s) + 1 - len(sub)):
result += (s[i:i + len(sub)] == sub)
return result