Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is string.find implemented in CPython?

Tags:

python

I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so http://docs.python.org/library/stdtypes.html is of no help. Could someone please point me to the relevant source code?

like image 664
saffsd Avatar asked Mar 25 '09 13:03

saffsd


People also ask

What is the use of string find () in Python?

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1. Parameters: sub: Substring that needs to be searched in the given string.

How is string implemented in Python?

Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.

How do I find a string in a string Python?

Using the 'in' operator: The in operator is the easiest and pythonic way to check if a python string contains a substring. The in and not in are membership operators, they take in two arguments and evaluate if one is a member of the other. They return a boolean value.

How do I find a string in a list Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.


3 Answers

The comment on the implementation has the following to say:

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

—https://github.com/python/cpython/blob/master/Objects/stringlib/fastsearch.h#L5

like image 135
SilentGhost Avatar answered Sep 26 '22 15:09

SilentGhost


You should be able to find it in Objects/stringlib/find.h, although the real code is in fastsearch.h.

like image 27
DNS Avatar answered Sep 24 '22 15:09

DNS


Looks like the algorithm used originates from Boyer-Moore-Horspool algorithm

like image 28
ismail Avatar answered Sep 23 '22 15:09

ismail