How can I find the first occurrence of a substring in a python string?

So, if my line is "dude - cool dude".
I would like to find the first dude index:

mystring.findfirstindex('dude') # should return 4 

What is the python command for this?
Thank.

+91
python string
Jul 11 2018-10-11T00:
source share
3 answers

find()

 >>> s = "the dude is a cool dude" >>> s.find('dude') 4 
+160
Jul 11 '10 at 4:50
source share

Short review: index and find

There is also an index next to the find method. find and index both give the same result: they return the position of the first occurrence,, but if nothing is found, index will raise a ValueError , while find return -1 , In speed both have the same test 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 the general case, find and index return the smallest index where the line with the transfer is run, and rfind and rindex returns the largest index to which it runs Most string search algorithms look from left to right , so functions starting with r show that the search comes from from right to left .

Therefore, if the likelihood that the item you are looking for is close to the end than to the top of the list, rfind or rindex will 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

+18
Dec 19 '17 at 5:31 on
source share

implement this in an algorithmic way without using the built-in Python function. It can be implemented as

 def find_pos(string,word): for i in range(len(string) - len(word)+1): if string[i:i+len(word)] == word: return i return 'Not Found' string = "the dude is a cool dude" word = 'dude1' print(find_pos(string,word)) # output 4 
0
Jan 30 '19 at 6:29
source share



All Articles