检查一个字符串,如果它不包含列表中的所需元素,则输出 false

Check a String and output false if it doesn't contain the desired element from a List

有人能帮我为什么这个代码变成真而我想让它变成假,因为我想要这样的输出:
是的字符串确实包含 x 但也包含 Y 让我们说 x 是 asd Y 是 asd 2(space) 我的代码是:

text = "asd 1"
Should_contain = ["asd 1"]
Shouldnt_contain = ["asd", "asdd"]
contains_desired_string = any(x in text for x in Should_contain)
contains_bad_string = any(x in text for x in Shouldnt_contain)
print(contains_desired_string, contains_bad_string)

(如果列表中有任何不需要的元素,它应该打印 False)。
所以它应该打印 True False INSTEAD of True True
我认为可能是因为 space.
的问题 例如,如果这是一个抓取 iphone 列表的网络爬虫,假设有一个 iphone 6 和一个 iphone 6s,bot 包含 iphone 6 但这两个列表是完全不同的,因此过滤它们是有意义的,是的,它包含 iphone 6 但它也包含 iphone 6s,因此程序会让你知道这是 iphone 6 还是 iphone 6s 列表,我希望这是下一个问题的明确答案

Any 函数 returns 如果 bool(x) 对于可迭代对象中的任何 x 为真则为真。在您的情况下,contains_bad_string 为真,因为输入字符串 text 包含 'asd',它是 Shouldnt_contain 列表中的一个元素。

根据您的评论 If any of the not wanted elements are in the List, it should print False ,您可以这样更改 contains_bad_string

contains_bad_string =  not any(x in text for x in Shouldnt_contain)

解决方案:

counter = 0
    if "asd" in text:
        counter = -1
    counter_haha = 0

    for x in Should_contain:
        counter +=text.count(x)

    for x in Shouldnt_contain:
        counter_haha += text.count(x)

    if (counter > 1 and counter_haha > 0) or counter == 0:
        print(text+"That means Yes it contains X and contains Y too")
    elif counter == 1 and counter_haha == 1:
        print(text+"That means Yes it contains X but it does not contain Y")

(X=asd 1 Y=asd 或 asdd)
例如,如果这是一个抓取 iphone 列表的网络爬虫,假设有一个 iphone 6 和一个 iphone 6s,bot 包含 iphone 6 但这两个列表是完全不同的,因此像这样过滤它们是有意义的,是的,它包含 iphone 6 但它也包含 iphone 6s,因此程序会让你知道这是 iphone 6 还是 iphone 6s 列表,我希望这是下一个问题的明确答案