+ 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 Antwort
+ 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