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>Your first code doesn't work because</p>

<pre><code>for char in s:
</code></pre>

<p>just sets <code>char</code> to individual characters in the string. So if <code>s = "bob is bob"</code>, <code>char</code> will be <code>"b"</code>, <code>"o"</code>, <code>"b"</code>, <code>"i"</code>, etc. None of those single-character strings starts with <code>"bob"</code>, so the <code>if</code> test will never succeed.</p>

<p>There's no built-in looping syntax for looping over substrings, so you need to iterate the index.</p>

python