186

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?

5 Answers 5

314

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
4
  • 47
    It returns -1 if not found Commented Apr 27, 2017 at 12:49
  • what if I want to find the word is from the sentence this is a cool dude ? I tried the find method but it returns index 2 instead of 5. How do i achieve this using find() ?
    – Regressor
    Commented Apr 12, 2020 at 23:09
  • 1
    @Regressor: look into regex and word boundaries. Commented Apr 12, 2020 at 23:29
  • 1
    @Regressor You could also just do s.find(" is ")+1 which granted feels a bit hacky but works fine.
    – Eog
    Commented Aug 11, 2022 at 9:00
57

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

2
  • if the string is defined as input_string = "this is a sentence" and if we wish to find the first occurrence of the word is , then will it work? # first occurence of word in a sentence input_string = "this is a sentence" # return the index of the word matching_word = "is" input_string.find("is")
    – Regressor
    Commented Apr 12, 2020 at 3:00
  • @Regressor you might want to search for the string with spaces on either end: 'this is a sentence'.find(' is ') Commented Oct 30, 2021 at 21:32
3

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'
print(find_pos(string,word))
# output 4
0
def find_pos(chaine,x):

    for i in range(len(chaine)):
        if chaine[i] ==x :
            return 'yes',i 
    return 'no'
2
  • 7
    Seems like your indentation is off and you forgot to close out your quotation marks. Explanation of your code and why it would solve the problem is helpful as well; see How to Answer
    – camille
    Commented Jan 14, 2020 at 19:59
  • sorry i edit it... my code find the first occurance of a letter in string and return his place Commented Jan 15, 2020 at 20:02
0

verse = "If you can keep your head when all about you\n 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

print(verse)
#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))
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.