string.count issue (i'm stupid?)

bruno at modulix onurb at xiludom.gro
Mon May 22 07:54:49 EDT 2006


Matteo Rattotti wrote:
> Hi all,
> 
> i've noticed a strange beaviour of string.count:
> 
> in my mind this code must work in this way:
> 
> str = "a_a_a_a_"

dont use 'str' as an identifier, it shadows the builtin str type.

> howmuch = str.count("_a_")
> print howmuch -> 3
> 
> but the count return only 2
> 
> Ok this can be fine, but why? The doc string tell that count will
> return the number of substring in the master string, if we spoke about
> substring i count 3 substring...

depends on how you define "number of substring", I mean, overlapping or
not. FWIW, I agree that this may be somewhat unintuitive, and would at
least require a little bit more precision in the docstring.

> Can someone explain me this? 

It seems obvious that str.count counts non-overlapping substrings.

> And in which way i can count all the
> occurrence of a substring in a master string? (yes all occurrence
> reusing already counter character if needed)

Look at the re module.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list