简体   繁体   English

如何检查 python 中字符串中的这个或那个字符?

[英]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当我只使用一个字符串或字符来检查字符串中的出现时,它可以正常工作,但是当我使用两个字符串(字符串中的“a”或“b”)时,它就不起作用了


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:对于以下情况,我个人更喜欢 lambda:

# 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): .你应该做if("a" in i or "b" in i):而不是if("a" or "b" in lst):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM