Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are str.count('') and len(str) giving different output?

Look at following code and please explain why the str.count('') method and len(str) function is giving two different outputs.

a=''
print(len(a))
print(a.count(''))

Output:

0
1
like image 540
liberal Avatar asked Oct 22 '16 12:10

liberal


People also ask

What is the difference between Len and count?

length method= len() => It's return number of element from value of variable. count method = count() =>It's return how many times appeared from value of variable which you are specified value. Because in "list1" which has total value inside is 4. So that's why it becomes output 4 by using len() method.

How does count () work in Python?

Count() is a Python built-in function that returns the number of times an object appears in a list. The count() method is one of Python's built-in functions. It returns the number of times a given value occurs in a string or a list, as the name implies.

What does the string method count () do?

The count() method returns the number of times a specified value appears in the string.

Is count faster than for loop Python?

count method can do its looping at C speed, which is faster than an explicit Python loop.


1 Answers

str.count() counts non-overlapping occurrences of the substring:

Return the number of non-overlapping occurrences of substring sub.

There is exactly one such place where the substring '' occurs in the string '': right at the start. So the count should return 1.

Generally speaking, the empty string will match at all positions in a given string, including right at the start and end, so the count should always be the length plus 1:

>>> (' ' * 100).count('')
101

That's because empty strings are considered to exist between all the characters of a string; for a string length 2, there are 3 empty strings; one at the start, one between the two characters, and one at the end.

So yes, the results are different and they are entirely correct.

like image 199
Martijn Pieters Avatar answered Oct 22 '22 19:10

Martijn Pieters