not in 的用法详解not in 是 Python 中一个非常实用的成员运算符(membership operator),用于判断某个元素是否不包含在序列(如列表、字符串、元组、集合等)中。它是 in 运算符的逻辑反。
element not in sequence
如果 element 不在 sequence 中,表达式返回 True;否则返回 False。
not inforbidden = ['admin', 'root', 'guest']
username = 'user123'
if username not in forbidden:
print("用户名可用")
else:
print("用户名被禁止")
输出:用户名可用
not insentence = "Hello, welcome to Python world!"
if "Java" not in sentence:
print("这句话没有提到 Java")
输出:这句话没有提到 Java
numbers = [1, 2, 3, 4, 5, 6]
exclude = [2, 4]
filtered = [x for x in numbers if x not in exclude]
print(filtered) # [1, 3, 5, 6]
not in 对大小写敏感(尤其在字符串中)not in 可能影响性能,建议使用 set 提升查找效率__contains__ 方法支持 not in 操作如果你需要多次检查元素是否不在一个集合中,将列表转换为 set 会更高效:
bad_words = set(['spam', 'scam', 'fraud'])
text = "This is a safe message."
# 高效检查
if not any(word in text for word in bad_words):
print("内容安全")