2016-11-18 26 views
0

對於我的任務,我被要求創建一個函數,如果單詞在字符串中,它將返回單詞的索引,並返回( - 1)如果單詞是不是字符串創建一個函數,它將索引python中的字符串中的單詞

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行...但我不知道如何返回列表中的一個字的位置。非常感謝您的幫助!

+1

嘗試加入'打印(目標)for循環,看看它在做什麼。 –

+2

另請參閱:[list.index()](https://docs.python.org/2/tutorial/datastructures.html) –

+0

您是否想通過索引或其值查找列表中的值?您需要使用不同的方法,具體取決於您嘗試實現的目標。 –

回答

0

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

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

+0

它使這種方式更有意義! – Alek

+0

upvote如果它解決您的問題。樂於幫助。 –

1

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

+0

我認爲他不被允許,因爲這是練習編碼(循環和事物)的功課。 – Maroun

+0

沒有,我會使用這些方法,如果我可以... – Alek

0

要找到一個詞的索引ALIST使用.index()功能和安全退出你的代碼字的時候沒有發現使用exception.Shown如下:

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 
相關問題