Multiple value checks using 'in' operator (Python)

前端 未结 7 1654
我寻月下人不归
我寻月下人不归 2020-11-29 07:37
if \'string1\' in line: ...

... works as expected but what if I need to check multiple strings like so:

if \'string1\' or \'string2         


        
相关标签:
7条回答
  • 2020-11-29 08:07

    also as for "or", you can make it for "and". and these are the functions for even more readablity:

    returns true if any of the arguments are in "inside_of" variable:

    def any_in(inside_of, arguments):
      return any(argument in inside_of for argument in arguments)
    

    returns true if all of the arguments are in "inside_of" variable:

    same, but just replace "any" for "all"

    0 讨论(0)
  • 2020-11-29 08:11
    if 'string1' in line or 'string2' in line or 'string3' in line:
    

    Would that be fine for what you need to do?

    0 讨论(0)
  • 2020-11-29 08:11

    1. You have this confusion Because you don't understand how the logical operator works with respect to string.

      Python considers empty strings as False and Non empty Strings as True.

      Proper functioning is :

      a and b returns b if a is True, else returns a.

      a or b returns a if a is True, else returns b.

      Therefore every time you put in a non empty string in place of string1 the condition will return True and proceed , which will result in an undesired Behavior . Hope it Helps :).

    0 讨论(0)
  • 2020-11-29 08:22

    If you read the expression like this

    if ('string1') or ('string2') or ('string3' in line):
    

    The problem becomes obvious. What will happen is that 'string1' evaluates to True so the rest of the expression is shortcircuited.

    The long hand way to write it is this

    if 'string1' in line or 'string2' in line or 'string3' in line:
    

    Which is a bit repetitive, so in this case it's better to use any() like in Ignacio's answer

    0 讨论(0)
  • 2020-11-29 08:22

    or does not behave that way. 'string1' or 'string2' or 'string3' in line is equivalent to ('string1') or ('string2') or ('string3' in line), which will always return true (actually, 'string1').

    To get the behavior you want, you can say if any(s in line for s in ('string1', 'string2', 'string3')):.

    0 讨论(0)
  • 2020-11-29 08:27
    if any(s in line for s in ('string1', 'string2', ...)):
    
    0 讨论(0)
提交回复
热议问题