Python Forum

Full Version: Problem with comparison operator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm writing a program that converts a blocklist into a BIND9 zones file for a blackhole/sinkhole DNS server. Within the script I have code similar to the following:

# The following list is just for the sake of illustration, the actual list comes from reading the blocklist file
my_list = ["foo.com/index.html", "bar.com/downloads/malware.exe", "conteso.com/phishing/email.htm", "domain.com/blog/test", "[Adblock]", "another.domain.com/another/test/blog", "blah.net/blah/blah/blah"]

for i in my_list:
    if(i != "[Adblock]"):
        print("This block should only execute if i is NOT equal to [Adblock].")
The issue is that the if block ALWAYS executes, whether i is equal to [Adblock] or not. I've tried escaping the brackets ("\[Adblock\]") but that didn't help either. I also tried single quotes and single quotes while escaping the brackets.

Any help would be greatly appreciated.
It works OK, all I've added is an else
# The following list is just for the sake of illustration, the actual list comes from reading the blocklist file
my_list = ["foo.com/index.html", "bar.com/downloads/malware.exe", "conteso.com/phishing/email.htm", "domain.com/blog/test", "[Adblock]", "another.domain.com/another/test/blog", "blah.net/blah/blah/blah"]
 
for i in my_list:
    if(i != "[Adblock]"):
        print("This block should only execute if i is NOT equal to [Adblock].")
    else:
        print("This block should only execute if i is equal to [Adblock].")
Outputs
Output:
This block should only execute if i is NOT equal to [Adblock]. This block should only execute if i is NOT equal to [Adblock]. This block should only execute if i is NOT equal to [Adblock]. This block should only execute if i is NOT equal to [Adblock]. This block should only execute if i is equal to [Adblock]. This block should only execute if i is NOT equal to [Adblock]. This block should only execute if i is NOT equal to [Adblock].
Thank you for looking into this Yoriz.
I haven't tried an else there. What I found that did work (and it contains an else Big Grin ) is:
# The following list is just for the sake of illustration, the actual list comes from reading the blocklist file
my_list = ["foo.com/index.html", "bar.com/downloads/malware.exe", "conteso.com/phishing/email.htm", "domain.com/blog/test", "[Adblock]", "another.domain.com/another/test/blog", "blah.net/blah/blah/blah"]
  
for i in my_list:
    if(re.match('\[Adblock\]', i)):
        next
    else:
        print("This should print only if i is NOT equal to [Adblock].")