arassi
arassi

Reputation: 139

Reducing 'if in' statement in Python

I have a list of strings and want to use various different operators to to pick out the string that satisfies my conditions.

The example code below gives me the answer I'm looking for:

strings = ['abc','bcd','cde','dea', 'eab']        
for string in strings:
    if 'a' in string and not 'b' in string and ('ea' not in string or 'd' in string):    
    print(string)
>> dea

However, this code requires me to write out 'in string' multiple times, which looks messy and takes time when referencing a number of conditions.

I want to know if there's a way to condense the code down to show that everything operator is searching -in string-

I would imagine the syntax looks something like:

strings = ['abc','bcd','cde','dea', 'eab']        
for string in strings:
    if ('a' and not 'b' and ('ea' not or 'd')) in string:    
        print(string)

but when I try this I get a SyntaxError.

Is there a pythonic way to condense the code?

Upvotes: 2

Views: 110

Answers (5)

kantal
kantal

Reputation: 2407

You can use regular expressions, but it is not so readable:

import re

reg=re.compile(r"(?=.*a.*)(?!.*b.*)(?:(?!.*ea.*)|(?=.*d.*))\w+")

for string in strings:
    mo=reg.fullmatch(string)
    if mo:
        print(mo.group())

Upvotes: 0

figbeam
figbeam

Reputation: 7176

You could use functions to make the if statement more easily read. As long as you keep the function definitions near the if statement readability should be ok.

strings = ['abc','bcd','cde','dea', 'eab']

def ye(c): return c in string
def no(c): return c not in string

for string in strings:
    if ye('a') and no('b') and (no('ea') or ye('d')):    
        print(string)

Upvotes: 1

zipa
zipa

Reputation: 27869

You can use eval() to evaluate expression like this one:

for string in strings:
    if eval("'a' {0} and not 'b' {0} and ('ea' not {0} or 'd' {0})".format("in string")):
        print(string)

Upvotes: 1

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

strings = ['abc','bcd','cde','dea', 'eab']        
for string in strings:
    if 'a' in string and 'b' not in string:
        if 'd' not  in string or 'ea' in string:    
            print(string)

Upvotes: 0

xnx
xnx

Reputation: 25478

The most Pythonic approach is to make your code as readable and expressive as possible. In your case, I would use two if statements:

for string in strings:
    if 'a' in string and 'b' not in string:
        if 'ea' not in string or 'd' in string:
             print(string)

dea

Upvotes: 2

Related Questions