Home > Enterprise >  Python check if one of multiple strings contain a substring
Python check if one of multiple strings contain a substring

Time:03-08

I have relatively complicated if statements that return True if a target string contains a keyword (also a string). Is there a way that as an elif I search for the keyword in multiple target strings?

This is my sample code:

a = 'i am foo'
b = 'keyword could also be in here'

if 'foo' in 'b':
    out = 1
elif 'foo' in [a,b]:
    out = 2
else:
    out = 3

Current behavior: returns 3 Expected behavior: return 2

I know that I could do elif 'foo' in a or 'foo' in b but my conditions are already lengthy with any and all statements so that the code becomes rather unreadable when I solve the issue with or.

Basically, I'm looking for a pythonic way to do this (only not in JavaScript).

Thanks!

CodePudding user response:

If you don't necessarily have to use if-statements, you can do

list(filter(lambda x:'foo' in x, [a,b]))

which will give you a list of strings containing 'foo'. So you if you just want to see IF some string contains your keyword, check if the length of this list is bigger 0, like so:

len(list(filter(lambda x:'foo' in x, [a,b]))) > 0

CodePudding user response:

I cannot explain why 'foo' in [a, b]: is not evaluating as True.

I am providing this answer as an expansion of the question to see if someone can explain in comments, why 'foo' in [a, b]: is not evaluating as True.

a = 'i am foo'
b = 'keyword could also be in here'

id([a,b]) # Is the ID ao the list in memory it contains the id of a and the id
# of b.
print(f'{id(a)=}')
print(f'{id([a,b][0])=}')
print(f'{id(b)=}')
print(f'{id([a,b][1])=}')

if 'foo' in 'b':
    out = 1
elif 'foo' in [a, b]:  # Does not evaluate as expected
    out = 2
elif 'foo' in str([a, b]):  # Will evaluate but why is it necessary
    out = 4
else:
    out = 3

print(f'{out}')

print(f"{'foo' in 'b'=}")
print(f"{'foo' in [a, b]=}")  # Does not evaluate as expected
print(f"{'foo' in str([a,b])=}")  # Will evaluate but why is it necessary
print(f"{'i am foo' in [a, b]=}")

Output:

id(a)=2165458290096
id([a,b][0])=2165458290096
id(b)=2165458558672
id([a,b][1])=2165458558672
4
'foo' in 'b'=False
'foo' in [a, b]=False
'foo' in str([a,b])=True
'i am foo' in [a, b]=True
  • Related