0

If I have a string str1=boobbobobpzfsbobboobbobb and I want to count how many times the string 'bob' is present inside it. However, I cannot use str1.count as it only counts non overlapped strings. SO what do I do?

0

4 Answers 4

2

Using regular expression (positive lookahead assertion):

>>> import re
>>> str1 = 'boobbobobpzfsbobboobbobb'
>>> sum(1 for m in re.finditer('b(?=ob)', str1))
4
Sign up to request clarification or add additional context in comments.

Comments

2

You can solve it in quadratic time (worst case) by considering all the substrings starting at an increasing index and counting how many start with "bob":

str1 = "boobbobobpzfsbobboobbobb"

times = 0   
for pos in range(len(str1)):
    if str1[pos:].startswith("bob"):
        times += 1

print(times)

or:

str1  = "boobbobobpzfsbobboobbobb"

times = sum(1 for x in range(len(str1)) if str1[x:].startswith("bob"))

print(times)

Comments

0
import re

str1 = 'boobbobobpzfsbobboobbobb'

len(re.findall('b(?=ob)',str1)) 

Comments

0

Here's a little one-liner for it:

str1 = "boobbobobpzfsbobboobbobb"
str2 = 'bob'

count = sum([str1[k:k+len(str2)]==str2 for k in range(0, len(str1)-len(str2)+1)])

# OUTPUT: 4

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.