python - String instead of integer in finding "bob" -
my question code:
count = 0 char in s: if char.startswith("bob"): count += 1 print ("number of times bob occurs is: " + str(count))
i have solution followed:
count = 0 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 solution using integer "for in range(len(s))", want alternative solution using character/string. tell me why above solution returns "0" in finding "bob"? thanks.
what wrong first piece of code become apparent print statement in loop. statement for char in s
loops through each character in s
, no character starts word bob
.
if want for in something
type loop, can do:
count = 0 word in s.split(): if word == "bob": count += 1 print ("number of times bob occurs is: " + str(count))
this work if wan match occurrences of bob occur word alone. if want match bob anywhere, use string.count method:
count = s.count("bob")
or alternatively, regex:
import re count = len(re.findall("bob", s))
if want overlapping answers. doing in loop more concisely. don't think there simpler way count overlapping occurrences this.
[s[i:i+3] in range(len(s))].count('bob')
Comments
Post a Comment