String instead of integer in finding "bob"
<p>My question code:</p>

<pre><code>count = 0

for char in s:

    if char.startswith("bob"):

        count += 1

print ("Number of times bob occurs is: " + str(count))
</code></pre>

<p>I have a good solution as followed:</p>

<pre><code>count = 0

for i in range(len(s)):

     if s[i: i+3] == "bob"

        count += 1

print ("Number of times bob occurs is: " + str(count))
</code></pre>

<p>My question: Instead of taking out a solution using integer "for i in range(len(s))", I want an alternative solution using character/string. Could anyone tell me why my above solution returns "0" in finding "bob"? Thanks.</p>

<p>What is wrong with your first piece of code will become apparent with a print statement in the loop. The statement <code>for char in s</code> loops through each character in <code>s</code> and no character starts with the word <code>bob</code>.</p>

<p>If you really want a <code>for something in something</code> type loop, you can do:</p>

<pre><code>count = 0
for word in s.split():
    if word == "bob":
        count += 1
print ("Number of times bob occurs is: " + str(count))
</code></pre>

<p>This will only work if you wan to match only occurrences of bob that occur as a word alone. If you want to match bob anywhere, use the string.count method:</p>

<pre><code>count = s.count("bob")
</code></pre>

<p>Or alternatively, regex:</p>

<pre><code>import re
count = len(re.findall("bob", s))
</code></pre>

<p>If you want overlapping answers. This is actually what you are doing in your for loop but more concisely. I don't think there is any simpler a way to count overlapping occurrences than this.</p>

<pre><code>[s[i:i+3] for i in range(len(s))].count('bob')
</code></pre>

python