Search code examples
pythonlistsearchcontain

Iterate through a list and return the element that contains a specific word


i have this code below:

wordSearch = "ghi"
lst = ['c:/test/abc.bat','c:/test/test1/def.bat','c:/123/ghi.exe','c:/test/testing/aa/jkl.bat']

by searching "ghi" I would like it to return "c:/123/ghi.exe". So, ultimately i want it to iterate through the list and return an element that contains specific text.

Many thanks.


Solution

  • Use a list comprehension like this:

    [item for item in lst if wordSearch in item]
    

    The above line will return any item that contains wordSearch.

    Output:

    >>> wordSearch = "ghi"
    >>> lst = ['c:/test/abc.bat','c:/test/test1/def.bat','c:/123/ghi.exe','c:/test/testing/aa/jkl.bat']
    >>> 
    >>> [item for item in lst if wordSearch in item]
    ['c:/123/ghi.exe']