Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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 - Fatal编程技术网

Python 我怎样才能让那些代码只返回一次?

Python 我怎样才能让那些代码只返回一次?,python,string,Python,String,“假设s是一个小写字符字符串 编写一个程序,打印字符串“bob”在s中出现的次数。例如,如果s='azcbobobeghakl',则程序应打印“ 到目前为止,这是我的代码 for i in range(len(s)): if s[i:i+3] == "bob": count += 1 print("Number of times bob occurs is: " + str(count)) 然而,我不断得到: bob发生的次数为:0 bob发生的次数为:0 bo

“假设s是一个小写字符字符串

编写一个程序,打印字符串“bob”在s中出现的次数。例如,如果s='azcbobobeghakl',则程序应打印“

到目前为止,这是我的代码

  for i in range(len(s)):
    if s[i:i+3] == "bob":
        count += 1
  print("Number of times bob occurs is: " + str(count))
然而,我不断得到:

bob发生的次数为:0 bob发生的次数为:0 bob发生的次数为:0 bob发生的次数为:1 bob发生的次数为:1 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2 bob发生的次数为:2


我试着让它只返回或打印2

您的代码缩进似乎不正确。不是在这里的帖子,但可能在真正的代码。我试过你的程序,结果只打印了一次。print语句应该在循环之外,即在相同的缩进级别。

显示的代码只打印一次。没有明显的问题。你显然遗漏了什么。我无法复制你的输出。如果你识别得很好,答案应该是bob出现的次数是:2.你的问题中缺少一个数字,并且重叠的处理没有得到明确的解决。这就是问题所在,我想这是我缺少的。