2016-09-17 136 views
-2

我需要編寫一個程序來打印字符串'bob'在s中出現的次數。例如,如果s =「azcbobobegghakl」,那麼該程序應該打印:2
想使用:mystring.find('bob'),但林不知道這個...如何在文本文件中查找字符串

+1

到目前爲止,你到底做了些什麼? – chenchuk

+3

先清楚你的問題。可能是這個鏈接可能幫助http://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-given-substring-in-a-string 謝謝 – Sagar

+0

謝謝,鏈接實際上讓我答案:S =在範圍 'xbxbxbbobobxvbcvbgb' SB = '鮑勃' 結果= 0 sub_len = LEN(SB) 對於i(LEN(S)): 如果s [I:+ sub_len] ==某人: results + = 1 print(「發生的'bob'發生的次數是:'」+ str(結果)) – troy

回答

0

str.find將返回該串出現的位置。例如:

"abc".find ("b") # Returns 1, because it is found at index 1 in the string array. 

的發現出現在列使用的數量:

"ababac".count ("ba") # Returns 2, because there are 2 "ba" in the string. 

瞭解更多關於str.count這裏:count string occurences

0

這是我設法得到答案。可能是很多人之一:

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