string.count issue (i'm stupid?)

Alexandre Fayolle alf at merlin.fayauffre.org
Mon May 22 07:19:33 EDT 2006


Le 22-05-2006, Matteo <matteo.rattotti at gmail.com> nous disait:
> 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_"
> 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...
>
> Can someone explain me this? 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)

Use the optional start argument of find or index in a loop, such as: 

>>> def count_all(string, substring):
...     index = 0
...     count = 0
...     while True:
...         index = string.find(substring, index)  
...         if index < 0:
...             return count
...         else:
...             count += 1
...             index += 1
... 
>>> count_all("a_a_a_a_", '_a_')
3


-- 
Alexandre Fayolle                              LOGILAB, Paris (France)
Formations Python, Zope, Plone, Debian:  http://www.logilab.fr/formations
Développement logiciel sur mesure:       http://www.logilab.fr/services
Python et calcul scientifique:           http://www.logilab.fr/science



More information about the Python-list mailing list