简体   繁体   中英

Write a program that prints the number of times the string contains a substring

s = "bobobobobobsdfsdfbob"
count = 0 
for x in s : 
    if x == "bob" : 
       count += 1
print count

i want to count how many bobs in string s, the result if this gives me 17 what's wrong with my code i'm newbie python.

When you are looping overt the string, the throwaway variable will hold the characters, so in your loop x is never equal with bob .

If you want to count the non-overlaping strings you can simply use str.count :

In [52]: s.count('bob')
Out[52]: 4

For overlapping sub-strings you can use lookaround in regex:

In [57]: import re

In [59]: len(re.findall(r'(?=bob)', s))
Out[59]: 6

you can use string.count

for example:

s = "bobobobobobsdfsdfbob"
count = s.count("bob")
print(count)

I'm not giving the best solution, just trying to correct your code.

Understanding what for each (aka range for) does in your case

for c in "Hello":
    print c  

Outputs:

H
e
l
l
o

In each iteration you are comparing a character to a string which results in a wrong answer.
Try something like
(For no overlapping, ie no span)

s = "bobobobobobsdfsdfbob"
w = "bob"
count = 0
i = 0
while i <= len(s) - len(w):
    if s[i:i+len(w)] == w:
        count += 1
        i += len(w)
    else:
        i += 1
print (count)

Output:

Count = 4

Overlapping

s = "bobobobobobsdfsdfbob"
w = "bob"
count = 0
for i in range(len(s) - len(w) + 1):
    if s[i:i+len(w)] == w:
         count += 1
print (count)

Output:
Count = 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM