0

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:
      
2020db9
  • 153
  • 1
  • 9
  • 1
    What is `cars` and why aren't you using the `car` iteration variable? – Barmar Jun 23 '22 at 20:44
  • https://docs.python.org/3/library/re.html#re.Pattern.match – thebjorn Jun 23 '22 at 20:44
  • `substring in string` doesn't need a wildcard in python. Using `model` instead of `car` in your iteration, and the difference of `or not` vs `and not` are what's messing you up – G. Anderson Jun 23 '22 at 20:47

1 Answers1

2

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]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • this is exactly what I was looking for. I'm used to % as a wildcard in SQL and I tried researching wildcard characters for Python, but was having no success. Your solution solved my problem. – 2020db9 Jun 23 '22 at 20:51
  • You don't need a wildcard if you just want to match a substring. This is like `IF LOCATE(model, 'car')` from SQL -- you don't need a wildcard there, either.\ – Barmar Jun 23 '22 at 20:52
  • `model.endswith()` might be more applicable here. – Axe319 Jun 23 '22 at 21:00