Python list logic error

I am trying to cut lines containing "msi" using regular expressions and list comprehension. However, when I print the list, lines containing "msi" are still in the list. What would be the mistake? This is my code:

 spam_list = [l for l in spam_list if not re.match("msi", l)] 
+4
source share
3 answers

re.match() matches the beginning of a line. Use re.search() or even better, in .

 L = [l for l in L if "msi" not in l] 
+10
source

Since you are apparently looking at a list of file names, you can also use endswith:

 list = [l for l in list if l.endswith('.msi')] 
+5
source

Here is one way to filter a list by file extension

 import os extensions = set(['.msi', '.jpg', '.exe']) L = [l for l in L if os.path.splitext(l)[1] not in extensions] 
+4
source

All Articles