nobody
nobody

Reputation: 1989

Python list comprehension logic error

I'm trying to weed out strings that contains "msi" using regular expressions and a list comprehension. However, when I print the list, strings that contain "msi" are still in the list. What exactly would the error be? This is my code:

spam_list = [l for l in spam_list if not re.match("msi", l)]

Upvotes: 4

Views: 401

Answers (3)

John La Rooy
John La Rooy

Reputation: 304175

Here is one way to filter a list by the file extension

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

Upvotes: 4

Manny D
Manny D

Reputation: 20724

Since you're apparently looking through a list of filenames, you could also use endswith:

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

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

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

L = [l for l in L if "msi" not in l]

Upvotes: 10

Related Questions