Python-成员运算符
时间:2020-02-23 14:43:00 来源:igfitidea点击:
在本教程中,我们将学习Python中的Membership运算符。
我们使用成员资格运算符来检查项的成员资格以给定的序列(例如元组,列表或者字符串)进行。
以下是Python中的成员运算符
- in
- not in
in运算符
如果给定项目在序列中,则此运算符将返回True。
否则,它返回False。
例子1
在下面的示例中,我们有一个字符串"快速的棕色狐狸跳过了懒狗"。
并且我们正在使用in
运算符检查字符串" fox"是否在字符串中。
haystack = "The quick brown fox jumps over the lazy dog." needle = "fox" result = needle in haystack print("result:", result)
我们将得到" True",因为给定的字符串中包含单词" fox"。
例子2
在下面的示例中,我们有一个列表,我们正在使用in运算符检查值10是否在列表中。
haystack = [1, 15, 10, 5, -99, 100] needle = 10 result = needle in haystack print("result:", result)
我们将得到True,因为列表中存在10。
not in
运算符
如果给定项不在序列中,则此运算符返回True。
否则,它返回False。
例子1
在下面的示例中,我们有一个字符串"快速的棕色狐狸跳过了懒狗"。
我们正在使用not in
运算符检查字符串" doe"是否不在字符串中。
haystack = "The quick brown fox jumps over the lazy dog." needle = "doe" result = needle not in haystack print("result:", result)
我们将得到" True",因为单词" doe"不在给定的字符串中。
例子2
在下面的示例中,我们使用" not in"运算符检查" Hello"是否不在给定的元组中。
haystack = ('theitroad', 9.1, True) needle = "Hello" result = needle not in haystack print("result:", result)
我们将得到" True",因为在元组中不存在" Hello"。