[Answer]-Python: more concise logic/syntax on empty strings

2πŸ‘

βœ…

if input is not None and (
   not var_a or var_a not in input or  # Should this be 'or' or 'and'? 'or' looks unusual here
   not var_b or var_b not in input):
    pass

You can skip checks for var_a != '' because after var_a == '' or they will always be True. Check var_a == '' is equivalent to not var_a if var_a can’t be None (and I guess it can’t be, because you don’t check for it)

Edit:

Now that I think of it you can also factor not out of the second bracket:

if input is not None and not(
   var_a and var_a in input and
   var_b and var_b in input):
    pass

… or out of the whole expression:

if not (input is None or 
        var_a and var_a in input and
        var_b and var_b in input):
    pass
πŸ‘€Kolmar

0πŸ‘

By definition if var_a or var_b are not falsey i.e empty they must be True so you only need a single check, not a check for both conditions:

I would nest an any inside an if inp is not None:

if inp is not None:
    if any((not var_a, var_a not in inp, not var_b, var_b not in inp)):
        # do whatever

In [26]: var_a = ""

In [27]: var_b = ""

In [28]: inp = "foo"

In [29]: (not var_a, var_a not in inp, not var_a, var_a not in inp)
Out[29]: (True, False, True, False)

-1πŸ‘

list = [var_a, var_b, input]
if '' in list == FALSE:
        if var_a is in input or var_b is in input:
           # do something
else:
   #do something    
πŸ‘€Kyle Coventry

Leave a comment