Suppose we want to compute a or b
. The or
operator works like this:
- If
a
is truthy, return a
- Otherwise, return
b
.
If you have more than two operands, for example, a or b or c or d
, it's equivalent to a or (b or (c or d))
, so it will work according to this algorithm:
- If
a
is truthy, return a
- Otherwise, if
b
is truthy, return b
- Otherwise, if
c
is truthy, return c
- Otherwise, return
d
.
So this expression: ('browser' or 'chrome') in 'start chrome'
will not work as you expect it to. First, ('browser' or 'chrome')
will evaluate to 'browser'
(because 'browser'
is truthy, as is any non-empty string), and 'browser' in 'start chrome'
is False
.
What you might want to use is:
('browser' in 'start chrome') or ('chrome' in 'start chrome')
Or you can use any
, coupled with a generator comprehension:
string = 'start chrome'
if any(substring in string for substring in ['browser', 'chrome', 'chromium']):
print('Ta da!')
Or, if you really like map
,
if any(map(string.__contains__, ['browser', 'chrome', 'chromium'])):
print('Ta da!')
Basically, any
returns True
if at least one element of the given iterable is truthy
.
a and b and c
works similarly to or
:
1. If a
is falsey, return a
1. Otherwise, if b
is falsey, return b
1. Otherwise, return c
What you might want to use in place of your and
-y expression is:
('start' in 'start chrome') and ('chrome' in 'start chrome')
Or you can use all
, which is like any
, but implements and
-logic instead or or
-logic: https://docs.python.org/3/library/functions.html#all