Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading