Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If substring in string, when substring has multiple values

I know there is a way to work around it, but I want to understand the underlying logic as to why this doesn't work.

It's a very simple statement, and it only returns as True when the first substring in the "or list" is shown.

for i in list:
    if (substring1 or substring2 or substring3) in string:
        print(string + " found!")

What am I missing here? I would think the or conditions would equal true if any substring was found in the string. As is, I'm only coming up as true if substring1 is found in string, and no substring2 or substring3.

like image 856
vbiqvitovs Avatar asked May 28 '26 21:05

vbiqvitovs


1 Answers

substring1 or substring2 or substring3

Assuming that substring1 is not the empty string, this expression evaluates to substring1 because substring1 is truthy. This is then checked to see if it's in string. The other substrings have no effect on the statement.

In other words, the ors are evaluated before the in, and the or evaluates to the first truthy value it finds (this is called short-circuiting). You can't use in that way to check whether multiple substrings are in a string.

You want:

substring1 in string or substring2 in string or substring3 in string

Or:

substrings = (substring1, substring2, substring3)
if any(s in string for s in substrings):
like image 196
kindall Avatar answered May 31 '26 09:05

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!