Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

python - Number of occurrences of a substring in a string

I need to count the nunber of times the substring 'bob' occurs in a string.

Example problem: Find the number of times 'bob' occurs in string s such that

"s = xyzbobxyzbobxyzbob"  #(here there are three occurrences)

Here is my code:

s = "xyzbobxyzbobxyzbob"

numBobs = 0

while(s.find('bob') >= 0)
   numBobs = numBobs + 1
   print numBobs

Since the find function in Python is supposed to return -1 if a substring is unfound the while loop ought to end after printing out the incremented number of bobs each time it finds the substring.

However the program turns out to be an infinite loop when I run it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For this job, str.find isn't very efficient. Instead, str.count should be what you use:

>>> s = 'xyzbobxyzbobxyzbob'
>>> s.count('bob')
3
>>> s.count('xy')
3
>>> s.count('bobxyz')
2
>>>

Or, if you want to get overlapping occurrences, you can use Regex:

>>> from re import findall
>>> s = 'bobobob'
>>> len(findall('(?=bob)', s))
3
>>> s = "bobob"
>>> len(findall('(?=bob)', s))
2
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...