Bob Counter in Python

后端 未结 8 1296
名媛妹妹
名媛妹妹 2021-01-28 11:25

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:



        
8条回答
  •  醉梦人生
    2021-01-28 11:38

    let's see if we can help you out.

    Your code is

    s='bobbbobobboobobookobobbobbboj'
    
     for i in s:
    
         if(i=='BOB' or i=='bob'):
            b=b+1
    

    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.

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

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

    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

提交回复
热议问题