Python:假与 0

时间:2023-04-14
本文介绍了Python:假与 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 PHP 中,您使用 === 表示法来测试 TRUEFALSE1 或<代码>0.

In PHP you use the === notation to test for TRUE or FALSE distinct from 1 or 0.

例如 if FALSE == 0 返回 TRUEif 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 False0 is not False).

  • The is operator 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 = {}, then a 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"*20 in most implementations, due to how Python handles string interning. This behavior isn't guaranteed, though, and you probably shouldn't be using is in this case. "a"*255 == "a"*255 and is almost always the right comparison to use.
  • 12345 is 12345 但在大多数实现中 12345 不是 12345 + 1 - 1,类似地.您几乎总是希望在这些情况下使用相等.
  • 12345 is 12345 but 12345 is not 12345 + 1 - 1 in most implementations, similarly. You pretty much always want to use equality for these cases.

这篇关于Python:假与 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:将 pandas 数据框中的列从 int 转换为 string 下一篇:是否有内置或更多 Pythonic 方式来尝试将字符串解析为整数

相关文章