Check substring match of a word in a list of words

后端 未结 3 1287
旧时难觅i
旧时难觅i 2021-01-06 20:30

I want to check if a word is in a list of words.

word = \"with\"
word_list = [\"without\", \"bla\", \"foo\", \"bar\"]

I tried if word

3条回答
  •  轮回少年
    2021-01-06 20:50

    in is working as expected for an exact match:

    >>> word = "with"
    >>> mylist = ["without", "bla", "foo", "bar"]
    >>> word in mylist
    False
    >>> 
    

    You can also use:

    milist.index(myword)  # gives error if your word is not in the list (use in a try/except)
    

    or

    milist.count(myword)  # gives a number > 0 if the word is in the list.
    

    However, if you are looking for a substring, then:

    for item in mylist:
        if word in item:     
            print 'found'
            break
    

    btw, dont use list for the name of a variable

提交回复
热议问题