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
4 Answers 4
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")
answered Nov 6, 2019 at 3:42
Channa
3,9277 gold badges47 silver badges72 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You don't even need brackets,
if "a" in i or "b" in i:
answered Nov 6, 2019 at 3:44
Sin Han Jinn
6825 silver badges19 bronze badges
Comments
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]
answered Nov 6, 2019 at 3:46
Yaakov Bressler
12.7k5 gold badges66 silver badges96 bronze badges
Comments
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
answered Nov 6, 2019 at 3:48
lenik
23.6k4 gold badges38 silver badges44 bronze badges
Comments
lang-py
inhas higher precedence thanoryou haveif "a" or ("b" in i). And"a"is always "truthy"