Why does "www".count("ww") return 1 and not 2?
Question:
In my code:
>> s = 'abacaba'
>> s.count('aba')
>> 2
For the above code I am getting the correct answer as ‘aba’ occurs 2 times in the string s
.
But for the following case:
>> s = 'www'
>> s.count('ww')
>> 1
In this case I am expecting that s.count('ww')
will return 2
. But it returns 1
.
Why?
Answers:
Read the docs:
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.
Since “ww” is first matched, it proceeds from the third “w” and fails to match “ww”.
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.
Just try to think it like:
In this word: “abacaba”, how many non-overlapping “aba” words do you see? I see 2. And I also see a “c”.
In this word: “www” how many non-overlapping “ww” words do you see? I see 1. And I also see a “w”.
For a better explanation, think that you are deleting the instance when you see.
For “abacaba” you see “aba” and delete it. now there is “caba”, you see “aba” again and delete it. now you get only “c”. you see “aba” two times. It is same for the “www”, you see “ww” once and delete it. now you see only “w”. you have seen “ww” once only.
It makes sense.
In my code:
>> s = 'abacaba'
>> s.count('aba')
>> 2
For the above code I am getting the correct answer as ‘aba’ occurs 2 times in the string s
.
But for the following case:
>> s = 'www'
>> s.count('ww')
>> 1
In this case I am expecting that s.count('ww')
will return 2
. But it returns 1
.
Why?
Read the docs:
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.
Since “ww” is first matched, it proceeds from the third “w” and fails to match “ww”.
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.
Just try to think it like:
In this word: “abacaba”, how many non-overlapping “aba” words do you see? I see 2. And I also see a “c”.
In this word: “www” how many non-overlapping “ww” words do you see? I see 1. And I also see a “w”.
For a better explanation, think that you are deleting the instance when you see.
For “abacaba” you see “aba” and delete it. now there is “caba”, you see “aba” again and delete it. now you get only “c”. you see “aba” two times. It is same for the “www”, you see “ww” once and delete it. now you see only “w”. you have seen “ww” once only.
It makes sense.