文字列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))
[position + 1:position + 2]文が正しく機能していないようです。どのように私は "b"の後ろに2つの文字を入力するのですか?
[重複する文字列カウント]の複製があります。(https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) –