+ 1
a = "hello"
Why does a.count("") give 6 ?
4 Antworten
+ 12
str.count("") always outputs len(str)+1
here, len(a) = 5, so, a.count("") = 6.
In other words, there are actually 6 empty strings.
1--> after the first " and before 'h'
2--> after 'h'
3--> after 'e'
4--> after 'l'
5--> after second 'l'
6--> after 'o' and before the last "
edited
+ 3
Thanks, I didn't know that...
But... How is it possible? I mean, a naive implementation of count would be :
len(list(filter(lambda c : c == "", a)))
Which will return 0...
Do you know how it is implemented?
+ 3
Probably implemented using regular expressions, as we got same result by doing:
import re
a = "hello"
r = re.compile("")
print(len(re.findall(r,a)))
+ 2
Huh... crazy! How does that happen? 😅