ROBlackSnail ROBlackSnail - 5 days ago 5
Python Question

Python 3.5.2 : Checking characters in a string form a list not the same as checking using !=

I wanted to write a program that filters the letter "m" or "M" in a string.
While using this version :

sentence = "Therem are a lotm of Ms in here andm iM hope tmo find then amll"
not_good = ["m", "M"]
result = list(filter(lambda x : x not in not_good,sentence))
result1 = "".join(result)
print(result1)


Gave me what I wanted :
There are a lot of s in here and i hope to find then all


When i tried this version of the code :

sentence = "Therem are a lotm of Ms in here andm iM hope tmo find then amll"

result = list(filter(lambda x : x != "m" or x != "M" ,sentence))

result1 = "".join(result)

print(result1)


It printed out sentence :
Therem are a lotm of Ms in here andm iM hope tmo find then amll


Also if i wanted to make a string that contains ONLY the "m"s and "M"s using this code :

result = list(filter(lambda x : x == "m" or x == "M" ,sentence))
result1 = "".join(result)
print(result1)


It workded just fine; i got :
mmMmMmm


Why didn't the second version of the code did its job while the first one did ?
Also, while
==
worked, why didn't
!=
?

Maybe I can't use =! to search through a string ? Don't think so ...

Please help a beginner programmer!

Also english is not my first language, so I am sorry for any mistakes.

Answer

What you wanted was the inversion of the condition x == "m" or x == "M", and you could instead do not (x == "m" or x == "M") for that case.

As to why x != "m" or x != "M" does not work the way you want, you can see that if x is m, x is obviously not M, so the condition is True and thus the character will pass through the filter and end up in your result.

A more formal way to express this is via De Morgan's Law, but in short, for this case:

not (x == "m" or x == "M") -> (x == "m" and x == "M")

Also for the original, incorrect case that we had; while not what we want, the following expressions are identical.

(x != "m" or x != "M") -> not (x != "m" and x != "M")

Comments