why "g".count('')==2 ?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Mar 11 14:15:16 CET 2006


On Sat, 11 Mar 2006 13:37:05 +0100, Fredrik Lundh wrote:

> "ygao" wrote:
> 
>> my question is as title!
> 
> my answer as code:
> 
>>>> s = "g"
>>>> t = ""
>>>> s[0:0+len(t)] == t
> True
>>>> s[1:1+len(t)] == t
> True


Or in other words, imagine that Python is walking the string looking to
match the target. The empty string matches the boundary of every character
with the next character, or in other words, for a string s of length N,
s.count('') will equal N+1.

I'm not sure what to describe this surprising result as. It isn't a bug;
it isn't even really a gotcha. I guess the best description is that it is
just a surprising, but logical, result.

(Well, I was surprised -- but I can't fault the logic.)


-- 
Steven.




More information about the Python-list mailing list