Python中的鲍勃计数器 [英] Bob Counter in Python

查看:64
本文介绍了Python中的鲍勃计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 2.7,我试图计算短语bobbbobobboobobookobobbobbboj"中bob"的出现次数.为此,我编写了以下代码:

Using Python 2.7, I was attempting to count the number of occurances of 'bob' in the phrase 'bobbbobobboobobookobobbobbboj.' To do this, I wrote the code below:

  b=0
  string='bobbbobobboobobookobobbobbboj'
  string = string.lower()

  for i in string:
     if(([i:i+3]=="bob") or ([i:i+3]=="BOB")'):
        b=b+1

  print ("Number of times bob occurs is:%s" %b)

但是,当我运行它时,它输出 0.

However, when I run it, it outputs 0.

推荐答案

看看我们能不能帮到你.

let's see if we can help you out.

您的代码是

s='bobbbobobboobobookobobbobbboj'

 for i in s:

     if(i=='BOB' or i=='bob'):
        b=b+1

考虑这一点很重要——像s"这样的字符串是一个字符列表.当您在 s 中执行 for i 时,您将遍历每个单独的字符.

It is important to think about this- a string like "s" is a list of characters. When you do for i in s, you are looping through each individual character.

在第一次迭代中,i == 'b',在第二次迭代中它等于 'o',依此类推.

on the first iteration, i == 'b', on the second one it equals 'o' and so on.

您想要的是检查代码段的东西.一种方法是

What you want is something that checks sections of code. a way of doing that would be

for i in range(len(s)):
    if s[i:i+4] == "bob":

这样做的原因是 range 按顺序返回一个数字列表,所以它会变成 0, 1, 2, 3 ... [i:i+4] 部分根据它在字符串中的距离.对于您的字符串 s[0:2] 将是bob"(以 0 开头).

The reason this works is that range returns a list of numbers in order, so it will go 0, 1, 2, 3... the [i:i+4] part cuts out a section of the string based on the how far into the string it is. For your string s[0:2] would be "bob" (it starts with 0).

我留下了几个问题......例如,如果你让它运行到最后你会遇到一个问题(如果 s 是 10 个字符长并且你尝试执行 s[9:12] 你会得到一个错误) ...但这应该可以帮助你开始

I left several problems... for example, if you let it run to the end you'll have a problem (if s is 10 characters long and you try to do s[9:12] you will get an error) ... but that should help you get going

这篇关于Python中的鲍勃计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆