I need to write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then the program should print: 2
thought to use: mystring.find('bob')
but Im not sure about this...
Asked
Active
Viewed 92 times
-2

SurvivalMachine
- 7,946
- 15
- 57
- 87

troy
- 29
- 1
- 7
-
1what did u try so far ? – chenchuk Sep 17 '16 at 21:31
-
3clear you question first. may be this link might help http://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-given-substring-in-a-string Thanks – Sagar Sep 17 '16 at 21:40
-
thanks, the link actually led me to the answer: s = 'xbxbxbbobobxvbcvbgb' sb = 'bob' results = 0 sub_len = len(sb) for i in range(len(s)): if s[i:i+sub_len] == sb: results += 1 print("Number of times 'bob' occurs is: ' " + str(results)) – troy Sep 18 '16 at 09:14
-
@troy search on google and on SO before posting – noɥʇʎԀʎzɐɹƆ Sep 18 '16 at 13:09
-
1Also, please don't post code on the comments. If you have an answer, it can go below *as an answer* – OneCricketeer Sep 18 '16 at 13:17
2 Answers
0
str.find
will return the position at which the string is found. For example:
"abc".find ("b") # Returns 1, because it is found at index 1 in the string array.
The find the number of occurrences in the string use:
"ababac".count ("ba") # Returns 2, because there are 2 "ba" in the string.
Read more on str.count
here: count string occurences

Community
- 1
- 1

Andrei Tumbar
- 490
- 6
- 15
0
this is the answer I managed to get to. probably one of many:
s = 'xbxbxbbobobxvbcvbgb'
sb = 'bob'
results = 0
sub_len = len(sb)
for i in range(len(s)):
if s[i:i+sub_len] == sb:
results += 1
print("Number of times 'bob' occurs is: ' " + str(results))

troy
- 29
- 1
- 7