Search code examples
pythonpython-3.xsetuser-input

check if user input contains set element in python


spam = {"make a lot of money","buy now","subscribe this","click this"}
text = input("Enter your text: ")
if (text in spam):
    print("It is spam")
else:
    print("it is not spam")

this code snippet is not working for the entered input
ex - text = "make a lot of money" , Output - "It is spam"
but if text = "click this to make a lot of money", Output - "it is not spam"

What is the possible explanation and the solution using the set method?


Solution

  • You could do something like this, I think your main problem is that you're not checking each item in the set, so unless the text is an exact match, you will not get the correct answer

    spam = {"make a lot of money","buy now","subscribe this","click this"}
    text = input("Enter your text: ")
    
    if any([x in text for x in spam]):
        print("It is spam")
    else:
        print("it is not spam")
    

    Using any allows you to compare each item in the set to the input to judge if at least one of them matches.