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


Given the string "the dude is a cool dude",
I’d like to find the first index of ‘dude’:

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

What is the python command for this?

Asked By: Shai UI




>>> s = "the dude is a cool dude"
>>> s.find('dude')
Answered By: mechanical_meat

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 and rindex return the largest index where it starts
Most of the string searching algorithms search from left to right, so functions starting with r 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

Answered By: user1767754

to implement this in algorithmic way, by not using any python inbuilt function .
This 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 = 'dude'
# output 4
Answered By: sahasrara62
def find_pos(chaine,x):

    for i in range(len(chaine)):
        if chaine[i] ==x :
            return 'yes',i 
    return 'no'
Answered By: Benmadani Yazid

verse = "If you can keep your head when all about youn Are losing theirs and blaming it on you,nIf you can trust yourself when all men doubt you,n But make allowance for their doubting too;nIf you can wait and not be tired by waiting,n Or being lied about, don’t deal in lies,nOr being hated, don’t give way to hating,n And yet don’t look too good, nor talk too wise:"

enter code here

#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
Answered By: Abideen Muhammed

If someone want to find first occurrence of sub-string in list of strings. Try this solution.

word_list = ['Today is a beautiful day', 'It is too hot today', 'the dude is a cool dude', 'today is a beautiful day']

search_str = 'beautiful day'

for item in word_list:
    if item.find(search_str) != -1:
Answered By: akshay_sushir
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.