Python 3.5.2:检查字符串中的字符形式与使用!=检查的列表不同

时间:2016-12-01 13:22:42

标签: python string python-3.x join lambda

我想写一个过滤字母" 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" s的字符串,使用此代码:

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

工作得很好;我得到了:mmMmMmm

为什么第二个版本的代码没有完成它的工作而第一个版本呢? 此外,虽然==有效,但为什么没有!=

也许我不能使用=!搜索字符串?不要这样想......

请帮助初学者程序员!

英语不是我的第一语言,所以我很抱歉任何错误。

2 个答案:

答案 0 :(得分:1)

您应该使用and而不是or

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

任何角色x != "m" or x != "M"始终为True的条件。

答案 1 :(得分:1)

您想要的是条件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")