Reputation: 141
When I used only a string or character to check occurrence in string then it works fine but when I used two strings ("a" or "b" in string) then it doesn't work
lst =["test in a", "test in b" "test b in a", "a test b", "test"]
for i in lst:
if("a" or "b" in lst):
print("true")
else:
print("false")
expected result:
true
true
true
true
false
Upvotes: 1
Views: 63
Reputation: 23498
Firstly, you're missing a comma ,
in your list. Once fixed that, try this:
>>> lst =["test in a", "test in b", "test b in a", "a test b", "test"]
>>> test_set = {'a', 'b'}
>>> for text in lst :
... print len(test_set & set(text)) > 0
...
True
True
True
True
False
Upvotes: 0
Reputation: 12018
You could shrink this to one line using list comprehensions as follows:
lst =["test in a", "test in b" "test b in a", "a test b", "test"]
test = [True if (("a" in i) or ("b" in i)) else False for i in lst]
I personally prefer lambdas for situations like these:
# This is written a bit wide, my style for these sort of things
f = lambda x: True if "a" in x else True if "b" in x else False
test = [f(i) for i in lst]
Upvotes: 0
Reputation: 3737
try this,
lst =["test in a", "test in b" "test b in a", "a test b", "test"]
for i in lst:
if any(item in i for item in ['a', 'b']):
print("true")
else:
print("false")
Upvotes: 3