tags:

views:

101

answers:

4
if 'string1' in line: ...

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

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

... doesn't seem to work.

+6  A: 
if any(s in line for s in ('string1', 'string2', ...)):
Ignacio Vazquez-Abrams
+1  A: 
if 'string1' in line or 'string2' in line or 'string3' in line:

Would that be fine for what you need to do?

aldld
Ofcourse, thats what I tried but I needed a more readable and efficient method. :)
Nimbuz
+1  A: 

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')):.

Mike Graham
+1  A: 

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

gnibbler