I'm still very much an beginner with Python (Spyder), more of my experience is with SQL and SAS. Therefore I'm unsure how to apply a wildcard to a string for conditional exclusion. For example, I have a list shown below and I want to exclude anything that ends with \New or \xNew.
Current List:
Model |
---|
Chrysler |
Chrysler\New |
Chrysler\xNew |
Ford\New |
Ford\xNew |
Ford |
Code that I tried to use:
for car in cars:
if '*\New' not in Model or '*\xNew' not in Model:
CodePudding user response:
You don't need the *
. And you need to use and
to combine the conditions, not or
(see Why does non-equality check of one variable against many values always return true?)
Backslash is the escape character in Python strings. If you want to match it literally, either double it or use a raw string.
for model in cars:
if r'\New' not in model and r'\xNew' not in model:
// do something
If you want a list of these models, you can use a list comprehension with the above condition:
new_cars = [model for model in cars if r'\New' not in model and r'\xNew' not in model]
CodePudding user response:
Since your question asks specifically for the usage of wildcards, you can use fnmatch for that purpose. It is a library that provides support for Unix-like wildcards.
Your code would, then, be
import fnmatch
excluded = [car for car in cars if fnmatch.fnmatch(car, "*\\New") or fnmatch.fnmatch(c"*\\xNew")]
Note that \\
is used in order to escape the backslash character.
Other approaches
For this specific case, another option would be using the endswith
function, that allows you to check if a string ends with a specific pattern. Your code would become the following:
excluded = [car for car in cars if car.endswith("\\New") or car.endswith("\\xNew")]
Another option can be the usage of Regular Expressions