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
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.
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.
The count() method returns the number of times a specified value appears in the string.
count method can do its looping at C speed, which is faster than an explicit Python loop.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With