-1

My question code:

count = 0

for char in s:

    if char.startswith("bob"):

        count += 1

print ("Number of times bob occurs is: " + str(count))

I have a good solution as followed:

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))

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.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
fandango
  • 3
  • 2
  • 2
    check out http://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-given-substring-in-a-string – Ben Sep 12 '16 at 21:24
  • No character starts with `"bob"`. `"bob"` is 3 characters long. – user2357112 Sep 12 '16 at 21:33
  • Possible duplicate of [Basic indexing recurrences of a substring within a string (python)](http://stackoverflow.com/questions/6987702/basic-indexing-recurrences-of-a-substring-within-a-string-python) – TemporalWolf Sep 12 '16 at 21:44
  • @TemporalWolf He already knows a correct way to do it. His question is why his first attempt didn't work, and that's not answered there. – Barmar Sep 12 '16 at 21:46
  • @Barmar The proper way to do what he wants to do is addressed in on the question. The question asked is a misunderstanding which, as written, is unlikely to benefit future users. -> user2357112's comment is probably sufficient and I'd advocate this should be closed. – TemporalWolf Sep 12 '16 at 21:54
  • @TemporalWolf This isn't the first time I've seen code like his. Questions based on common misunderstandings can help other people with the same misunderstanding. – Barmar Sep 12 '16 at 21:56

2 Answers2

0

Your first code doesn't work because

for char in s:

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

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you very much, Barmar! So, "char" stands for one character, even though I change "char" to "word", it still stands for one character, correct? What if I want to express "for somestring(not a single character) in one whole string (in this case, "s")"? Thanks. – fandango Sep 13 '16 at 20:26
  • `char` is just a variable name, it doesn't mean anything. The point is that when you use `for-in` with a string, the things you iterate over are the characters in the string. – Barmar Sep 13 '16 at 20:45
  • There's no built-in way to express iterating over substrings, you have to construct them explicitly using slices. – Barmar Sep 13 '16 at 20:46
0

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

If you really want a for something in something type loop, you can do:

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

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:

count = s.count("bob")

Or alternatively, regex:

import re
count = len(re.findall("bob", s))

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.

[s[i:i+3] for i in range(len(s))].count('bob')
gowrath
  • 3,136
  • 2
  • 17
  • 32
  • This will fail on `bobbob` or `Hi bob!". `string.split` separates tokens via whitespace. – TemporalWolf Sep 12 '16 at 21:57
  • 1
    @TemporalWolf The answer addresses that. – Barmar Sep 12 '16 at 21:57
  • Hi Gowrath, thank you very much! I like your second idea: "count = s.count("bob")", which is very simple. I wonder if I use this solution, would the entire code be: print s.count("bob")? I tried in one case: s = "bobbobfdsfadfobobobfd". There should be 4 "bobs", while it only returns 3 for me. Could you or anyone gives me a hint? – fandango Sep 13 '16 at 20:33
  • @fandango According to the docs, str.count "returns the number of (non-overlapping) occurrences of substring sub in string s." If you want the overlapping results, check the fourth thing I just added to the answer. – gowrath Sep 13 '16 at 20:41