0

is there a meaningful difference between:

z='xxx'
if z in ['xxx', 'yyy']:
if 'xxx' or 'yyy' in z:

will 'in' allow a partial and split string match?

if 'xx yy' in 'xx zz yy':

I spent all day bug hunting and it boiled down to the above. Otherwise the code is line for line identical. Worst part is both scripts worked, I was just having a hell of a time consolidating them. Both other people's legacy code on legacy/partial data with limited documentation. I fixed it in the end, but these are my lingering questions.

Crash
  • 15
  • 4
  • 1
    Does this answer your question? [How to test multiple variables against a single value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-single-value) The tl;dr is that `x or y in z` does not mean "is either x in z or y in z?" but rather "is x a truthy value, or is y in z" – that other guy Aug 27 '21 at 23:32

1 Answers1

0

Welcome Crash

Yes, there is a meaningful difference

z='xxx'
z in ['xxx', 'yyy']

is checking if the list contains 'xxx' which it does

if 'xxx' or 'yyy' in z:

will always return True since non-emptystrings are truthy; ie if ('xxx'): is True

You could re-write it more explicitly as

if 'xxx' or ('yyy' in z):

I believe what you'd be looking for is more like this:

if any([i in z for i in ['xxx', 'yyy']):

which checks if either 'xxx' or 'yyy' is in z

FWIW; there's also:

if all([i in z for i in ['xxx', 'yyy']):

regarding your question of

if 'xx yy' in 'xx zz yy':

that would only check for the exact string literal; if you wanted to look for both xx or yy there are a number of ways you could handle it but I would probably turn the first string into a lists and check the elements like this:

if all([i in 'xx zz yy' for i in 'xx yy'.split(" ")]):

which is the same as

if all([i in 'xx zz yy' for i in ['xx', 'yy']):
Schalton
  • 2,867
  • 2
  • 32
  • 44