On Sat, 11 Mar 2006 13:37:05 +0100, Fredrik Lundh wrote:
[color=blue]
> "ygao" wrote:
>[color=green]
>> my question is as title![/color]
>
> my answer as code:
>[color=green][color=darkred]
>>>> s = "g"
>>>> t = ""
>>>> s[0:0+len(t)] == t[/color][/color]
> True[color=green][color=darkred]
>>>> s[1:1+len(t)] == t[/color][/color]
> True[/color]
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.)
For the same reason as[color=blue][color=green][color=darkred]
>>> "".count("" )[/color][/color][/color]
1[color=blue][color=green][color=darkred]
>>> "ab".count( "")[/color][/color][/color]
3
This is counting slice positions, which is one more that the length of the
string.
Em Sáb, 2006-03-11 às 04:25 -0800, ygao escreveu:[color=blue]
> my question is as title!
> thanks![/color]
Forget it. Just look:
$ python2.4 -mtimeit '"g".count(" ")'
1000000 loops, best of 3: 0.516 usec per loop
$ python2.4 -mtimeit 'len("g")+1'
1000000 loops, best of 3: 0.26 usec per loop
Steven D'Aprano wrote:[color=blue]
> On Sat, 11 Mar 2006 13:37:05 +0100, Fredrik Lundh wrote:
>
>[color=green]
>>"ygao" wrote:
>>
>>[color=darkred]
>>>my question is as title![/color]
>>
>>my answer as code:
>>
>>[color=darkred]
>>>>>s = "g"
>>>>>t = ""
>>>>>s[0:0+len(t)] == t[/color]
>>
>>True
>>[color=darkred]
>>>>>s[1:1+len(t)] == t[/color]
>>
>>True[/color]
>
>
>
> 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.[/color]
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
Comment