Write a program that prints the number of times the string contains a substring
<pre><code>s = "bobobobobobsdfsdfbob"
count = 0 
for x in s : 
    if x == "bob" : 
       count += 1
print count
</code></pre>

<p>i want to count how many bobs in string s, the result if this gives me 17 
what's wrong with my code i'm newbie python.</p>

<p>When you are looping overt the string, the throwaway variable will hold the characters, so in your loop <code>x</code> is never equal with <code>bob</code>.</p>

<p>If you want to count the non-overlaping strings you can simply use <code>str.count</code>:</p>

<pre><code>In [52]: s.count('bob')
Out[52]: 4
</code></pre>

<p>For overlapping sub-strings you can use lookaround in regex:</p>

<pre><code>In [57]: import re

In [59]: len(re.findall(r'(?=bob)', s))
Out[59]: 6
</code></pre>

python python-2.7 python-3.x