Alek
Alek

Reputation: 5

Creating a function that will index a word in a string in python

For my assignment, I am asked to create a function that will return the index of a word in a string if the word is in the string, and return (-1) if the word is not in the string

bigstring = "I have trouble doing this assignment"
mywords = bigstring.split()
def FindIndexOfWord(all_words, target):
    index = mywords[target]
    for target in range(0, len(mywords)):
        if  target == mywords:
            return(index)
    return(-1)
print(FindIndexOfWord(mywords, "have"))

I am pretty sure my mistake is on line 4... but I don't know how to return the position of a word in a list. Your help would be much appreciated!

Upvotes: 0

Views: 90

Answers (3)

Taufiq Rahman
Taufiq Rahman

Reputation: 5714

To find the index of a word in alist use .index() function and for safety exiting your code when the word is not found use an exception.Shown below:

bigstring = "I have trouble doing this assignment"
mywords = bigstring.split()
def FindIndexOfWord(list,word):
    try:
        print(list.index(word))
    except ValueError:
        print(word," not in list.")

FindIndexOfWord(mywords,"have")

Output:

1

Upvotes: 0

Karan Nagpal
Karan Nagpal

Reputation: 341

you are making small mistakes. here is the correct code:

bigstring = "I have trouble doing this assignment"
mywords = bigstring.split()
def FindIndexOfWord(all_words, target):
    for i in range(len(mywords)):
        if  target == all_words[i]:
            return i
    return -1
print(FindIndexOfWord(mywords, "this"))

Target is a string and not a integer so you can't use

index = mywords[target]

and return the variable used in looping if string is found else -1

Upvotes: 0

denvaar
denvaar

Reputation: 2214

You can use .find(word) on the string to get the index of a word.

Upvotes: 1

Related Questions