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

S

Steven D'Aprano

ygao said:
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.)
 
T

Terry Reedy

For the same reason as3

This is counting slice positions, which is one more that the length of the
string.
 
F

Felipe Almeida Lessa

Em Sáb, 2006-03-11 às 04:25 -0800, ygao escreveu:
my question is as title!
thanks!

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


--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

-- Sun Tzu, em "A arte da guerra"
 
J

James Stroud

Steven said:
:

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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,289
Messages
2,571,448
Members
48,126
Latest member
ToneyChun2

Latest Threads

Top