Python: False vs 0(Python:假与 0)
问题描述
在 PHP 中,您使用 === 表示法来测试 TRUE 或 FALSE 与 1 或<代码>0代码>.
In PHP you use the === notation to test for TRUE or FALSE distinct from 1 or 0.
例如 if FALSE == 0 返回 TRUE,if FALSE === 0 返回 FALSE.因此,在以 0 为基数进行字符串搜索时,如果相关子字符串的位置正好在开头,您会得到 0,PHP 可以将其与 FALSE 区分开来.
For example if FALSE == 0 returns TRUE, if FALSE === 0 returns FALSE. So when doing string searches in base 0 if the position of the substring in question is right at the beginning you get 0 which PHP can distinguish from FALSE.
有没有办法在 Python 中做到这一点?
Is there a means of doing this in Python?
推荐答案
在 Python 中,
In Python,
is运算符测试身份(False is False,0 is not False).
The
isoperator tests for identity (False is False,0 is not False).
== 运算符,用于测试逻辑相等(因此 0 == False).
The == operator which tests for logical equality (and thus 0 == False).
从技术上讲,这些都不完全等同于 PHP 的 ===,后者比较逻辑相等和类型 - 在 Python 中,a == b 和 type(a) 是类型(b).
Technically neither of these is exactly equivalent to PHP's ===, which compares logical equality and type - in Python, that'd be a == b and type(a) is type(b).
is 和 == 之间的一些其他区别:
Some other differences between is and ==:
{} == {},但{} 不是 {}(列表和其他可变类型也是如此)- 但是,如果
a = {},则a 是一个(因为在这种情况下它是对同一个实例的引用)
{} == {}, but{} is not {}(and the same holds true for lists and other mutable types)- However, if
a = {}, thena is a(because in this case it's a reference to the same instance)
"a"*255 不是 "a"*255",但在大多数实现中,"a"*20 是 "a"*20,因为如何Python 处理字符串实习.但是,这种行为并不能保证,在这种情况下您可能不应该使用is."a"*255 == "a"*255并且几乎总是适合使用的比较.
"a"*255 is not "a"*255", but"a"*20 is "a"*20in most implementations, due to how Python handles string interning. This behavior isn't guaranteed, though, and you probably shouldn't be usingisin this case."a"*255 == "a"*255and is almost always the right comparison to use.
12345 is 12345但在大多数实现中12345 不是 12345 + 1 - 1,类似地.您几乎总是希望在这些情况下使用相等.
12345 is 12345but12345 is not 12345 + 1 - 1in most implementations, similarly. You pretty much always want to use equality for these cases.
这篇关于Python:假与 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:假与 0
基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
