2017-10-16 2 views
1

文字列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つの文字を入力するのですか?

+0

[重複する文字列カウント]の複製があります。(https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) –

答えて

1

第2スライスインデックスは含まれません。 s[position+1:position+2]は位置position + 1の1文字であり、この部分文字列はobには等しくないことを意味します。関連するanswerを参照してください。あなたは[:position + 3]が必要です

s = 'azcbobobegghakl' 
counter = 0 
numofiterations = len(s) 
position = 0 

#loop that goes through the string char by char 
for iteration in range(numofiterations - 2): 
    if s[position] == "b":     # search pos. for starting point 
     if s[position+1:position+3] == "ob": # check if complete 
      counter += 1   
    position +=1 

print("Number of times bob occurs is: " + str(counter)) 
# 2 
+0

位置+ 3が文字列の内側にあるかどうかを確認します。 ..またはチェックを常に有効にするために範囲を2に減らす –

+0

@RobertoTrani: 'position + 3'はエラーを起こさずに' len(s) 'より大きくすることができます。私は「範囲」を変えることができた、はい。 –

+0

これは必要ですか?私はちょうどこれをテストするために最後にbを追加し、うまくいった。私の理解から、それは単に "ob"と空の文字列を比較するでしょうか? – Ajaybee

0

あなたがインデックスに.findを使用することができます。あなたのアプローチが機能しなかった理由を

s = 'azcbobobegghakl' 

needle = 'bob' 

idx = -1; cnt = 0 
while True: 
    idx = s.find(needle, idx+1) 
    if idx >= 0: 
     cnt += 1 
    else: 
     break 

print("{} was found {} times.".format(needle, cnt)) 
# bob was found 2 times. 
0

Eric's answerは完全に説明する(Pythonでスライスがエンド排他的である)が、私が提案してみましょう別のオプション:

s = 'azcbobobegghakl' 
substrings = [s[i:] for i in range(0, len(s))] 
filtered_s = filter(substrings, lambda s: s.startswith("bob")) 
result = len(filtered_s) 

または単に

s = 'azcbobobegghakl' 
result = sum(1 for ss in [s[i:] for i in range(0, len(s))] if ss.startswith("bob")) 
+1

さて、「単純に」... – Jan

関連する問題