Why is this code output 6 instead of 5 | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

Why is this code output 6 instead of 5

x="12345" y=x.count("") print(y)

14th Feb 2023, 10:39 AM
Ravindu Dilshan
Ravindu Dilshan - avatar
1 Resposta
+ 2
Thatā€™s how count works in Python, your counting how many times a substring is present in a string. Your substring is empty, so if you look at your string: ā€œ12345ā€ - there are six occurences of ā€œā€, Iā€™ll illustrate with a *: ā€œ*1*2*3*4*5*ā€ - six ā€œā€ in your string. Hopefully that makes sense? Count works slightly different on lists, where it checks the number of times the substring (element) appears in the list. x=["123", "", "45"] y=x.count("") print(y) As an example will produce 1. As you tagged length, if you are looking for the string length then use len(str) instead: y = len(x) šŸ‘
14th Feb 2023, 12:20 PM
DavX
DavX - avatar