1

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
Jjj
6497 silver badges15 bronze badges
asked Nov 6, 2019 at 3:35
4
  • 2
    isn't it supposed to be if("a" in i) or ("b" in i) ? Commented Nov 6, 2019 at 3:38
  • yes, but if("a" or "b" in i) is same as if ("a" in i) or ("b" in i) or isn't it? Commented Nov 6, 2019 at 3:44
  • no that not how to use or condition in python, you want for it to represent A or B, you basically writing A or (B in i) Commented Nov 6, 2019 at 3:47
  • 1
    No. Because in has higher precedence than or you have if "a" or ("b" in i). And "a"is always "truthy" Commented Nov 6, 2019 at 3:49

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

You don't even need brackets,

if "a" in i or "b" in i:
answered Nov 6, 2019 at 3:44

Comments

0

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.