#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0

    Str.count('') | How does python count empty strings?


    Code:
    >>> len('a')
    1
    >>> 'a'.count('')
    2
    >>> len('aa')
    2
    >>> 'aa'.count('')
    3
    >>>
    At first glance it seems as if what it's doing is considering the string in this way

    Code:
     a     value
     0     index
    - -    empty positions
    
     a  a
     0  1
    -  -  -
    How would you explain it and maybe if you're willing, how would you write your own version of str.count() as a function.
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    615
    Rep Power
    65
    Makes sense if s.count('') counts the empty space around each character of string s. Two adjoining characters share the same empty space between them.
    After all ...
    Code:
    >>> ''.count('')
    1
    >>> s = '' + 'a' + ''
    >>> s
    'a'
    >>> s.count('')
    2
    >>>
    Last edited by Dietrich; November 4th, 2012 at 09:50 AM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0
    Originally Posted by Dietrich
    Makes sense if s.count('') counts the empty space around each character of string s. Two adjoining characters share the same empty space between them.
    After all ...
    Code:
    >>> ''.count('')
    1
    >>> s = '' + 'a' + ''
    >>> s
    'a'
    >>> s.count('')
    2
    >>>
    That does explain it more clearly. So the empty strings are like a padding. While tried to figure out how to code a count function that would simulate str.count I realized the count of the empty strings will always be the length plus 1. This is what I have.

    Code:
    def count(string, sub):
        if sub == '':
            return len(string) + 1
        else:
            total = 0
            ind = 0
            sub_len = len(sub)
            stop = len(string) - sub_len + 1
            while ind < stop:
                if string[ind:ind+sub_len] == sub:
                    total += 1
                    ind += sub_len
                else:
                    ind += 1
            return total
    I was playing around with and timing it and saw that explicit if else statements seem to be faster than a trailing if statement. Do you know of any other optimization tips?

IMN logo majestic logo threadwatch logo seochat tools logo