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

2024-06-10 00:53:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算子字符串“bob”在字符串s中出现的次数。我为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”后面的两个字符?你知道吗


Tags: 字符串loopforlenifthatcounterposition
3条回答

不包括第二个切片索引。这意味着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

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"))

可以将.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.

相关问题 更多 >