November 4th, 2012, 08:52 AM
Str.count('') | How does python count empty strings?
At first glance it seems as if what it's doing is considering the string in this way
How would you explain it and maybe if you're willing, how would you write your own version of str.count() as a function.
- - empty positions
- - -
November 4th, 2012, 09:37 AM
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 ...
>>> s = '' + 'a' + ''
Last edited by Dietrich; November 4th, 2012 at 09:50 AM.
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
November 5th, 2012, 02:27 AM
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.
Originally Posted by Dietrich
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?
def count(string, sub):
if sub == '':
return len(string) + 1
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
ind += 1