Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple value checks using 'in' operator (Python)

Tags:

python

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.

like image 958
eozzy Avatar asked Feb 22 '10 05:02

eozzy


3 Answers

if any(s in line for s in ('string1', 'string2', ...)):
like image 78
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 14:10

Ignacio Vazquez-Abrams


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

like image 21
John La Rooy Avatar answered Oct 18 '22 14:10

John La Rooy


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

Would that be fine for what you need to do?

like image 41
Eric Bannatyne Avatar answered Oct 18 '22 16:10

Eric Bannatyne