a = "hello" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

a = "hello"

Why does a.count("") give 6 ?

24th Apr 2020, 6:04 AM
MahirShah
4 Answers
+ 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
24th Apr 2020, 6:20 AM
M Tamim
M Tamim - avatar
+ 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?
24th Apr 2020, 7:20 AM
Théophile
Théophile - avatar
+ 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)))
25th Apr 2020, 1:47 AM
visph
visph - avatar
+ 2
Huh... crazy! How does that happen? 😅
24th Apr 2020, 8:21 AM
HonFu
HonFu - avatar