簡體   English   中英

創建一個將在python中的字符串中索引一個單詞的函數

[英]Creating a function that will index a word in a string in python

對於我的作業,要求我創建一個函數,如果單詞在字符串中,則該函數將返回字符串中單詞的索引,如果單詞不在字符串中,則返回(-1)

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"))

我很確定我的錯誤是在第4行...但是我不知道如何返回單詞在列表中的位置。 您的幫助將不勝感激!

您可以在字符串上使用.find(word)來獲取單詞的索引。

您正在犯小錯誤。 這是正確的代碼:

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"))

目標是字符串,而不是整數,因此您不能使用

index = mywords[target]

如果找到字符串,則返回循環中使用的變量,否則為-1

要在列表中查找單詞的索引,請使用.index()函數,並為安全起見在未找到該單詞時退出代碼,請使用異常。如下所示:

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")

輸出:

1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM