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

James Stroud jstroud at ucla.edu
Sat Mar 11 17:59:05 EST 2006


Steven D'Aprano wrote:
> 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.

Yes, but:

py> "gab".split("")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ValueError: empty separator

The idea is not consistent between string functions. I actually consider 
this latter example a bug.

Jaems

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list