check if user input contains set element in python

Question:

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?

Asked By: Suyash Srivastava

||

Answers:

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.

Answered By: Dominic Beyer
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.