2016-02-09 107 views
-4

我正在写一个函数,用户放入文本和单词,如果该单词在列表中,它将返回该单词在列表中的位置。从功能访问列表

list = ["hello", "goodbye", "name"]  

def fact(txt, my_list): 
    text = txt.split() 
    for i in range(0, len(my_list)): 
     for j in range(0, len(text)): 
      if(my_list[i] == text[i]): 
       return my_list[i] 

value = fact("hello, my name is", "name") 
print(value) 

但是,这似乎只是每次都没有返回。有没有特别的原因,它不工作?

+6

您的缩进看起来完全破裂。 –

+1

请不要在没有正确缩进的情况下发布代码,尤其是python代码。 – khelwood

+0

由于在Python中缩进是语法的一部分,请让sur代码正确缩进。 –

回答

0

例子:

def f(text, search): 
     if search in text.split(): 
      print('Word "{}" has been found @ index: {}'.format(search, text.split().index(search))) 

输出:

data = 'hello world, my name is -e' 
f(data, '-e') 

字 “-E” 已经发现@指数:5

+0

函数应该*返回*索引,而不是打印它。 – zondo

0

能正常工作

def getword(word, text): 
    text = text.replace(',', '') # remove ',' by nothing 
    tmp = text.split(' ') 
    if word in tmp: 
     print("word: [%s] find at index %s in this text:[ %s]" % (word, tmp.index(word), text)) 
     return tmp.index(word) 
    else: 
     print("Did not find [%s] in [%s]" % (word, text)) 
     return -1 


word = "what" 
text = "Hello, I am groot, what is your name" 

index = getword(word, text)