我想要計算字符串s中子字符串「bob」的出現次數。我爲edX課程做這個練習。如何使用切片符號計算特定的子字符串
s = 'azcbobobegghakl'
counter = 0
numofiterations = len(s)
position = 0
#loop that goes through the string char by char
for iteration in range(numofiterations):
if s[position] == "b": # search pos. for starting point
if s[position+1:position+2] == "ob": # check if complete
counter += 1
position +=1
print("Number of times bob occurs is: " + str(counter))
但是,似乎s [position + 1:position + 2]語句無法正常工作。我如何處理「b」後面的兩個字符?
可能重複的[字符串計數與重疊事件](https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) –