Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我应该如何改进我的Python代码?_Python_String_Count - Fatal编程技术网

我应该如何改进我的Python代码?

我应该如何改进我的Python代码?,python,string,count,Python,String,Count,该程序应打印字符串bob在字符串中出现的次数,例如:如果s=azcbobebeghakl,则程序应打印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

该程序应打印字符串bob在字符串中出现的次数,例如:如果s=azcbobebeghakl,则程序应打印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)
您可以这样使用re.findall:


也许像这样的事情不是很有效:

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

@AshwiniChaudhary注意到了这一点,使用re.findall和前瞻断言。可能是最快的。@RvdK不。它在某些情况下有效,但在其他情况下,它不能正确计数。只有工作代码属于那里。
def fn(s):
    cnt = 0
    n = len(s)
    for i in range(0, n):
        if s[i:i+3] == "bob":
            cnt += 1
    return cnt