2017-10-16 48 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)) 

但是,似乎s [position + 1:position + 2]語句無法正常工作。我如何處理「b」後面的兩個字符?

+0

可能重複的[字符串計數與重疊事件](https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) –

回答

1

不包括第二個切片索引。這意味着s[position+1:position+2]是位置position + 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:允許'位置+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

相關問題