简体   繁体   中英

Algorithm used to implement the Python str.count function

I came across the Python str.count function while reading the documentation. I can't seem to find any good explanation on the inner working of the function. What algorithm is used to count the number of substrings in a string? How does it actually work?

Study the source code at https://github.com/python/cpython/blob/master/Objects/stringlib/fastsearch.h

A comment at the top of file explains this much:

fast search/count implementation, based on a mix between boyer- moore and horspool, with a few more bells and whistles on the top. for some more background, see: http://effbot.org/zone/stringlib.htm

I've tried to do a simple code to count how many "r" in a List of words using Python:

fruit = ["apple", "banana", "rrrrrrrrr", "cherry", "berrada"]
y=0
for j in range(len(fruit)):
  x = fruit[j].count("r")
  y = y + x
  
print(y)

It might help you understand how the count function works.

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