Could someone help me why does this code turns TRUE while I want it to turn False, because i want the output like:
Yes the string does contain x but contains Y too let's say x is asd and Y is asd 2 (with space) There is my code :
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)
(If any of the not wanted elements are in the List, it should print False).
SO it should print True False INSTEAD of True True
I think that there might be the problem because of the space.
For example if that's a webscraper that scrapes iphone listings let's say there is an iphone 6 and a iphone 6s,bot contains iphone 6 but the two listings are whole differents ones, therefore it makes sense to filter them like ,yes it contains iphone 6 but it contains iphone 6s too,therefore the program will let you know if that's an iphone 6 or iphone 6s listing, I hope that's a clear anwser for the next questions
CodePudding user response:
Any functions returns True if bool(x) is True for any x in the iterable. In your case contains_bad_string
is true because the input string text
contains 'asd'
which is an element in Shouldnt_contain
list.
As per your comment If any of the not wanted elements are in the List, it should print False
, you can change contains_bad_string
in this way
contains_bad_string = not any(x in text for x in Shouldnt_contain)
CodePudding user response:
SOLUTION:
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 or asdd)
For example if that's a webscraper that scrapes iphone listings let's say there is an iphone 6 and a iphone 6s,bot contains iphone 6 but the two listings are whole differents ones, therefore it makes sense to filter them like ,yes it contains iphone 6 but it contains iphone 6s too,therefore the program will let you know if that's an iphone 6 or iphone 6s listing, I hope that's a clear anwser for the next questions