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
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")
You don't even need brackets,
if "a" in i or "b" in i:
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]
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
It's a simple typo.
You should do if("a" in i or "b" in i):
instead of if("a" or "b" in lst):
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.