我想编写一个过滤字符串中的字母“ m”或“ M”的程序。使用此版本时:
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)
给了我我想要的东西:There are a lot of s in here and i hope to find then all
当我尝试此版本的代码时:
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)
它打印出句子: Therem are a lotm of Ms in here andm iM hope tmo find then amll
另外,如果我想使用此代码制作仅包含“ m”和“ M”的字符串:
result = list(filter(lambda x : x == "m" or x == "M" ,sentence))
result1 = "".join(result)
print(result1)
它工作得很好。我有 :mmMmMmm
为什么第二个版本的代码没有完成而第一个版本的工作呢?另外,在==
工作时为什么不!=
呢?
也许我不能使用=!搜索一个字符串?不要这样...
请帮助初学者程序员!
此外,英语不是我的母语,因此,对于任何错误,我深表歉意。
您想要的是条件的倒置x == "m" or x == "M"
,而您可以not (x == "m" or x == "M")
针对这种情况做。
至于为什么x != "m" or x != "M"
不能按您想要的方式工作,您可以看到,如果x是m
,x显然不是M
,那么条件为True,因此该字符将通过过滤器并最终得到结果。
一种更正式的表达方式是通过戴摩根定律(De Morgan's Law),但简而言之,在这种情况下:
not (x == "m" or x == "M")
-> (x == "m" and x == "M")
同样对于我们原来的错误案例;虽然不是我们想要的,但以下表达式是相同的。
(x != "m" or x != "M")
-> not (x != "m" and x != "M")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句