Tula Magar
Tula Magar

Reputation: 141

how to check this or that characters in string in python?

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

Answers (4)

lenik
lenik

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

Yaakov Bressler
Yaakov Bressler

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

Sin Han Jinn
Sin Han Jinn

Reputation: 684

You don't even need brackets,

if "a" in i or "b" in i:

Upvotes: 0

Channa
Channa

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

Related Questions