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?
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.
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.
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.
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.
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
You should be able to find it in Objects/stringlib/find.h, although the real code is in fastsearch.h.
Looks like the algorithm used originates from Boyer-Moore-Horspool algorithm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With