Home > Net >  How to check if a String contains at least 2 elements from a list
How to check if a String contains at least 2 elements from a list

Time:01-13

For e.g the variable is a boolean : char_check = False

For e.g the string is "python i$ cool_123"(the string can vary depending on the input)

And the list is "[$, &, #, @,1,2,3]

If the string contains at least two elements from the list then char_check = True. But i only know how to check if a string contains one item from a list using the any() function, not 2 or multiple items in a list.

Any help or solutions will Be appreciated thank you

I tried using the any(function) but it only checks if a string contains at least one item not 2 or more

Tl:dr A string inputted should have at least two elements from a list

CodePudding user response:

This is a possible solution:

def check_chars(s, lst):
    return len(set(s) & set(lst)) >= 2

Examples:

>>> check_chars("abc", ["a", "d"])
False
>>> check_chars("abc", ["a", "c"])
True

Another option:

def check_chars(s, lst):
    it = iter(s)
    return any(c in lst for c in it) and any(c in lst for c in it)

CodePudding user response:

def func(string,lst):
    count=0
    for i in string:
        if i in lst:
            count =1
    if count>=2:
        return True
    else:
        return False
lst=['$', '&', '#', '@', '1', '2', '3']
string=input("Enter the sting:")
print(func(string,lst))

Hope it helped..

  • Related