Search code examples
python-3.xstringlistboolean-logicboolean-operations

How flexible is 'in' in Python e.g. if 'xxx' in yyy:


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.


Solution

  • 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']):