我应该如何改进Python代码?

2024-04-19 10:04:34 发布

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

该程序应打印字符串“bob”在字符串中出现的次数,例如:如果s=“azcbobobegbeghakl”,则程序应打印2。它在某些情况下起作用,但在其他情况下,它不能正确计算。有什么问题吗?你知道吗

numbob = 0
i = 0
if len(s) > 2:
    for letter in s:
        if letter == "b":
            if len(s) < 3:
                break
            i = s.index(letter)
            s = s[i: ]
            if s[0] == "b" and s[1] == "o" and s[2] == "b":
                numbob += 1
                s = s[2: ]
            else:
                s = s[i+1: ]
print(numbob)

Tags: and字符串in程序forindexlenif
2条回答

也许是这样(虽然效率不高):

def fn(s):
    cnt = 0
    n = len(s)
    for i in range(0, n):
        if s[i:i+3] == "bob":
            cnt += 1
    return cnt

您可以这样使用re.findall()

import re
>>> len(re.findall("(?=bob)", "azcbobobegghakl"))
2

相关问题 更多 >