Skip to content
Advertisement

Filter elements in a list not containing multiple substrings in Python

For a list of file names file_names, I try to use code below to filter file names not containing foo or bar:

JavaScript

Output:

JavaScript

But it’s not working out, it should return data.xlsx.

Meanwhile, it works for containing case:

JavaScript

Out:

JavaScript

Does someone could help to explain what’s error in my code and how to fix it? Thanks.

Reference:

Does Python have a string ‘contains’ substring method?

Advertisement

Answer

Since you don’t want any sub to be in the file names; one way is to wrap the inner loop with all:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement