string.count issue (i'm stupid?)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matteo Rattotti

    #1

    string.count issue (i'm stupid?)

    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)

    Thanks a lot

    Matteo Rattotti www.rknet.it
    Powered by:
    - MacOsX
    - Gnu / Linux Debian Sarge
    - Amiga Os 3.9
    - Milk

  • Dirk Hagemann

    #2
    Re: string.count issue (i'm stupid?)

    I think I can tell you WHY this happens, but I don't know a work-around
    at the moment.
    It seems as if only the following "_a_" (A) are counted: a_A_a_A_

    regards
    Dirk

    Comment

    • Diez B. Roggisch

      #3
      Re: string.count issue (i'm stupid?)

      Matteo Rattotti wrote:
      [color=blue]
      > 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...[/color]

      It appears to be a documentation bug. It should say something about
      non-overlapping occurences.

      Better would be of course to introduce a parameter that defines the
      behavior, either overlapping or not.

      Diez

      Comment

      • Alexandre Fayolle

        #4
        Re: string.count issue (i'm stupid?)

        Le 22-05-2006, Matteo <matteo.rattott i@gmail.com> nous disait:[color=blue]
        > 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)[/color]

        Use the optional start argument of find or index in a loop, such as:
        [color=blue][color=green][color=darkred]
        >>> def count_all(strin g, substring):[/color][/color][/color]
        .... index = 0
        .... count = 0
        .... while True:
        .... index = string.find(sub string, index)
        .... if index < 0:
        .... return count
        .... else:
        .... count += 1
        .... index += 1
        ....[color=blue][color=green][color=darkred]
        >>> count_all("a_a_ a_a_", '_a_')[/color][/color][/color]
        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

        Comment

        • Alexander Schmolck

          #5
          Re: string.count issue (i'm stupid?)

          "Dirk Hagemann" <DirkHagemann@g mail.com> writes:
          [color=blue]
          > I think I can tell you WHY this happens, but I don't know a work-around
          > at the moment.[/color]

          len(re.findall( '_(?=a_)', '_a_a_a_a_'))

          # untested
          def countWithOverla ps(s, pat):
          return len(re.findall( "%s(?=%s)" % (re.escape(pat[0]), re.escape(pat[1:])),s))

          'as

          Comment

          • bruno at modulix

            #6
            Re: string.count issue (i'm stupid?)

            Matteo Rattotti wrote:[color=blue]
            > 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_"[/color]

            dont use 'str' as an identifier, it shadows the builtin str type.
            [color=blue]
            > 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...[/color]

            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.
            [color=blue]
            > Can someone explain me this?[/color]

            It seems obvious that str.count counts non-overlapping substrings.
            [color=blue]
            > 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)[/color]

            Look at the re module.

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

            Comment

            • Tim Chase

              #7
              Re: string.count issue (i'm stupid?)

              I agree the docstring is a bit confusing and could be clarified
              as to what's happening
              [color=blue]
              > 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)[/color]


              You should be able to use something like

              s = "a_a_a_a_"
              count = len([i for i in range(len(s)) if s.startswith("_ a_", i)])

              which will count the way you wanted, rather than the currently
              existing count() behavior.

              -tkc



              Comment

              • BartlebyScrivener

                #8
                Re: string.count issue (i'm stupid?)

                We were doing something like this last week

                thestring = "a_a_a_a_"[color=blue][color=green][color=darkred]
                >>> for x in range(len(thest ring)):[/color][/color][/color]
                .... try:
                .... thestring.count ("_a_", x, x + 3)
                .... except ValueError:
                .... pass

                Comment

                Working...