How can I find the first occurrence of a sub-string in a python string?
find()
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
Quick Overview: index
and find
Next to the find
method there is as well index
. find
and index
both yield the same result: returning the position of the first occurrence, but if nothing is found index
will raise a ValueError
whereas find
returns -1
. Speedwise, both have the same benchmark results.
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
Additional knowledge: rfind
and rindex
:
In general, find and index return the smallest index where the passed-in string starts, and
rfind
andrindex
return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting withr
indicate that the search happens from right to left.
So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind
or rindex
would be faster.
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
Source: Python: Visual QuickStart Guide, Toby Donaldson