Python – “test”.count('')

  • A+

This is a short one, yet very irritating - i know i can count the amount of a certain string occuring within another string like

'banana'.count('a') >>>3 

meaning that banana contains the letter "a" 3 times.

and this is where it gets kind of weird.

my first confusion is - when i enter 'foo'.count(''), what does python look for?

is '' == None == anything? it doesnt seem to be the case, but then again, what IS '' logically speaking? and more important, why does

'test'.count('') >>>5 

happen? what the hell is included in a string thats always 1 higher than the amount of letters? the void?

EDIT: the ' character twice looks like one " character. i am talking about two times ' here, to avoid confusion

EDIT2: There seems to be unclearence about how the amount of '' happen, refer to below comments

Let's see, you are checking count('') which are always number of letters+1

See example:

s = '' + 'a' + '' s.count('') >> 2 >>> s 'a' 

Return the number of non-overlapping occurrences of substring sub.

Lets see in detail about this NULL character which is something like '/x00' in Python:

a = ''+''+'' >>> print(a.__sizeof__()) 37 >>> a = '/x00/x00/x00' >>> print(a.__sizeof__()) 40 

You can see the change in size using a null character. Null character is a character in Python.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: