+ 1
Why is this code output 6 instead of 5
x="12345" y=x.count("") print(y)
1 Answer
+ 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) đ