这篇教程python不等于运算符的具体使用写得很实用,希望能帮到您。 Python not equal operator returns True if two variables are of same type and have different values, if the values are same then it returns False.
如果两个变量具有相同的类型并且具有不同的值 ,则Python不等于运算符将返回True ;如果值相同,则它将返回False 。 Python is dynamic and strongly typed language, so if the two variables have the same values but they are of different type, then not equal operator will return True.
Python是动态的强类型语言,因此,如果两个变量具有相同的值,但它们的类型不同,则不相等的运算符将返回True 。 Python不等于运算符 (Python not equal operators)
Operator | Description | != | Not Equal operator, works in both Python 2 and Python 3. | <> | Not equal operator in Python 2, deprecated in Python 3. | 操作员 | 描述 | != | 不是Equal运算符,可在Python 2和Python 3中使用。 | <> | 在Python 2中不等于运算符,在Python 3中已弃用。 | Python 2示例 (Python 2 Example)
Let's see some examples of not-equal operator in Python 2.7. 我们来看一些Python 2.7中不等于运算符的示例。 $ python2.7Python 2.7.10 (default, Aug 17 2018, 19:45:58) [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> 10 <> 20True>>> 10 <> 10False>>> 10 != 20True>>> 10 != 10False>>> '10' != 10True>>> Python 3示例 (Python 3 Example)
Here is some examples with Python 3 console. 这是Python 3控制台的一些示例。 $ python3.7Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> 10 <> 20 File "<stdin>", line 1 10 <> 20 ^SyntaxError: invalid syntax>>> 10 != 20True>>> 10 != 10False>>> '10' != 10True>>> We can use Python not equal operator withf-strings too if you are using Python 3.6 or higher version. 如果您使用的是Python 3.6或更高版本,我们也可以将Python不等于运算符与f字符串一起使用。 x = 10y = 10z = 20 print(f'x is not equal to y = {x!=y}') flag = x != zprint(f'x is not equal to z = {flag}') # python is strongly typed languages = '10'print(f'x is not equal to s = {x!=s}') Output: 输出: x is not equal to y = False x is not equal to z = True x is not equal to s = True
Python不等于自定义对象 (Python not equal with custom object)
When we use not equal operator, it calls __ne__(self, other) function. So we can define our custom implementation for an object and alter the natural output. 当我们使用不等于运算符时,它将调用__ne__(self, other)函数。 因此,我们可以为对象定义自定义实现并更改自然输出。 Let's say we have Data class with fields Python字符串的拆分与连接详解 Django url反向解析的实现 |