python 成员运算符_Python的“ in”和“ not in”成员资格运算符

python 成员运算符

Python has two membership operators – “in” and “not in”. They are used to check if an element is present in a sequence or not.

Python有两个成员运算符-“ in”和“ not in”。 它们用于检查元素是否按顺序存在。

运算符中的Python (Python in Operator)

This operator returns True if the specified element is present in the sequence. The syntax of “in” operator is:

如果序列中存在指定的元素,则此运算符返回True。 “ in”运算符的语法为:


x in y

Here “x” is the element and “y” is the sequence where membership is being checked.

“ x”是元素,“ y”是检查成员资格的顺序。

Here is a simple program to show the usage of Python in operator.

这是一个简单的程序,用于显示运算符中Python的用法。


vowels = ['A', 'E', 'I', 'O', 'U']

ch = input('Please Enter a Capital Letter:\n')

if ch in vowels:
    print('You entered a vowel character')
else:
    print('You entered a consonants character')
Python In Operator Example 1
Python in Operator Example
运算符示例中的Python

Recommended Readings: Python input(), Python List

推荐读物Python input()Python列表

We can use the “in” operator with Strings and Tuples too because they are sequences.

我们也可以对字符串元组使用“ in”运算符,因为它们是序列。


>>> name='JournalDev'
>>> 'D' in name
True
>>> 'x' in name
False
>>> primes=(2,3,5,7,11)
>>> 3 in primes
True
>>> 6 in primes
False

我们可以在字典中使用Python“ in”运算符吗? (Can we use Python “in” Operator with Dictionary?)

Let’s see what happens when we use “in” operator with a dictionary.

让我们看看将“ in”运算符与字典一起使用会发生什么情况。


dict1 = {"name": "Pankaj", "id": 1}

print("name" in dict1)  # True
print("Pankaj" in dict1)  # False

It looks like the Python “in” operator looks for the element in the dictionary keys.

看起来像Python的“ in”运算符在字典键中寻找元素。

Python“不在”运算符 (Python “not in” Operator)

It’s opposite of the “in” operator. We can use it with sequence and iterables.

它与“ in”运算符相反。 我们可以将其与sequ​​ence和iterables一起使用。


>>> primes=(2,3,5,7,11)
>>> 6 not in primes
True
>>> 3 not in primes
False

翻译自: https://www.journaldev.com/38028/python-in-and-not-in-membership-operators

python 成员运算符

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值