如何使用切片表示法计算特定子字符串

时间:2017-10-16 20:17:48

标签: python

我想计算字符串s中子串“bob”的出现次数。我为edX课程做了这个练习。

AVCaptureVideoDataOutputSampleBufferDelegate

然而,似乎s [position + 1:position + 2]语句无法正常工作。我如何在“b”后面加上两个字符?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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.

答案 2 :(得分:0)

Eric's answer完全解释了为什么你的方法不起作用(在Python中切片是最终排他的),但让我提出另一个选择:

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

或只是

{{1}}