检查列表中的任何元素是否存在于字符串中

时间:2018-08-23 04:48:01

标签: python

这是一个我想打印 TRUE 的示例,因为Drug在字符串中。如果disease在字符串中,我也希望它也打印 TRUE 。对于所有其他情况,我想打印 FALSE

mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
check_if_in_mystring = ['Drug', 'Disease']

if check_if_in_mystring in mystring:
    print("TRUE")
else:
    print("FALSE")

6 个答案:

答案 0 :(得分:2)

您的示例是正确的,您可以对字符串使用“ in”运算符,只需在“ check_if_in_mystring”上添加循环即可遍历要检查的每个元素,如下面的示例。

mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
check_if_in_mystring = ['Drug', 'Disease']

for element in check_if_in_mystring:
    if element in mystring:
        print("TRUE for {}".format(element))
    else:
        print("FALSE for {}".format(element))

输出:

TRUE for Drug
FALSE for Disease

答案 1 :(得分:1)

此代码段将检测check_if_in_mystring中是否有mystring

any(word in mystring for word in check_if_in_mystring)

对于问题的确切行为:

print(str(any(word in mystring for word in check_if_in_mystring)).upper())

答案 2 :(得分:0)

尝试一下:

>>> my_string = "Drug   CID006338583    AC1O3UYX    Stitch  
1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"

>>> print("TRUE" if "Drug" in my_string or "Disease" in my_string else 
"FALSE")

TRUE

>>> my_string = "Some other random string"

>>> print("TRUE" if "Drug" in my_string or "Disease" in my_string else 
"FALSE")

FALSE

>>> my_string = "Has the word Disease"

>>> print("TRUE" if "Drug" in my_string or "Disease" in my_string else 
"FALSE")

TRUE

字符串支持in运算符,因此您只需检查Drug中是否包含Diseasemy_string

答案 3 :(得分:0)

将字符串转换为列表并签入列表可以是一种解决方案, 如下所述。

mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
check_if_in_mystring = ['Drug', 'Disease']
mystring1 = mystring.split() #convertin string to list, seprated by white space
for item in check_if_in_mystring:
    if item in mystring1:
        print(item)
        print("TRUE")
    else:
        print(item)
        print("FALSE")

输出:打印工作及其在mystring中的存在

Drug
TRUE
Disease
FALSE

答案 4 :(得分:0)

亚历克斯·泰勒(Alex Taylor)处在正确的轨道上,但是any子句可以大大简化:

>>> mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
>>> check_if_in_mystring = ['Drug', 'Disease']
>>> any(word in mystring for word in check_if_in_mystring)
True
>>> mystring =  "Poodle   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
>>> any(word in mystring for word in check_if_in_mystring)
False

这些方法在check_if_in_mystring中的单词列表中循环,一旦第一个any(...)表达式为Trueword in mystring返回True。如果for word in check_if_in_mystring循环结束而没有找到True值,则any(...)返回False。

答案 5 :(得分:0)

您还可以使用:

mystring.contains(anotherstring)