2016-11-18 60 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 
相关问题