从功能访问列表

时间:2016-02-09 11:55:10

标签: python list

我正在编写一个函数,其中用户放入文本和单词,如果单词在列表中,则返回列表中单词的位置。

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)

但是,这似乎每次都没有返回。是否有任何特殊原因导致无效?

2 个答案:

答案 0 :(得分: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”已找到@ index:5

答案 1 :(得分: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)