pythonlist

How to filter list of items based on substring?


I have a list which has collection of filepaths and i want to extract the paths which only contains 'mp4'.

lists = ['/Users/me/1. intro.mp4', 'The mp4 version.vlc'
         '/Users/2. intro.vtt', '/Users/1. ppt.rar', '/Users/2. ppt.mp4']

Expected output:

['/Users/me/1. intro.mp4', 'The mp4 version.vlc','/Users/2. ppt.mp4']

I tried the below code but its not exactly giving me the correct output. My code looks:

lists = ['/Users/me/1. intro.mp4',
         '/Users/2. intro.vtt', '/Users/1. ppt.rar', '/Users/2. ppt.mp4']


def Filter(string, substr):
    return [str for str in string if
            any(sub in str for sub in substr)]


searchString = 'mp4'
result = Filter(lists, searchString)
print(f'{result}')

If I run the program, it gives me the following output:

['/Users/me/1. intro.mp4', '/Users/1. ppt.rar', '/Users/2. ppt.mp4']

Can anybody tell me how to fix?


Solution

  • Try This:

    lists = ['/Users/me/1. intro.mp4',
             '/Users/2. intro.vtt', '/Users/1. ppt.rar', '/Users/2. ppt.mp4']
    
    def filterSubstr(lists, substr):
        return [x for x in lists if substr in x]
    
    searchString = 'mp4'
    print(filterSubstr(lists, searchString))
    

    Result:

    ['/Users/me/1. intro.mp4', '/Users/2. ppt.mp4']