Search code examples
pythonanacondaspyder

Conditional Exclusion with Strings


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:
      

Solution

  • 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]