Discussion Room : IDC101

Unexpected behavior of s.count(substr) when substr = ""

Unexpected behavior of s.count(substr) when substr = ""

by Dhruva Sambrani -
Number of replies: 4

Consider the following program:

s="IISER"
print s.count("I")
Output-
2

which was expected.


However consider this-

s="IISER"
print s.count("")
Output-
6

Why did we get 6 when there are only 5 characters?

Hint : This answer can be got to by trying to emulate count() without inbuilt functions.

In reply to Dhruva Sambrani

Re: Unexpected behavior of s.count(substr) when substr = ""

by Ayushman Srivastava . -

I tried emulating, and all this program returned was: 0


def countchar(S, s):

    # S is string to be examined, s is the character to be counted.

    count = 0
    for let in S:
        if(let == s):
            count +=1
    return count

print countchar("IISER", "")

In reply to Ayushman Srivastava .

Re: Unexpected behavior of s.count(substr) when substr = ""

by Kapil Paranjape -

You have misunderstood the definition of super.count(sub). It counts the number of occurrences of the sub-string sub in the string super.

There are 6 (count them!) occurrences of the empty string in the string "super".

Try to write the correct program to do what count does.

In reply to Dhruva Sambrani

Re: Unexpected behavior of s.count(substr) when substr = ""

by Dheer Mankad . -

I believe it initiates the first " " before the first "I", because it is the default string, so it considers the empty character as an extra subset. I might be wrong, however.

In reply to Dheer Mankad .

Re: Unexpected behavior of s.count(substr) when substr = ""

by Dhruva Sambrani -

Can you further elaborate on 

initiates the first " " before the first "I", because it is the default string

Also please give 1 or 2 outputs too.


Further, can you extend the program to take a substring of any size? (Presently you've only considered that the substring is only a single letter)