为什么这个字符串比较返回False?

2024-04-29 11:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
String comparison in Python: is vs. ==

algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm is "first")

我在命令行中用参数first运行它,那么为什么代码输出:

first
False

Tags: 命令行in参数stringissysalgorithmcomparison
3条回答

来自the Python documentation

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

这意味着它不检查值是否相同,而是检查它们是否在同一个内存位置。例如:

>>> s1 = 'hello everybody'
>>> s2 = 'hello everybody'
>>> s3 = s1

请注意不同的内存位置:

>>> id(s1)
174699248
>>> id(s2)
174699408

但由于s3等于s1,因此内存位置相同:

>>> id(s3)
174699248

使用is语句时:

>>> s1 is s2
False
>>> s3 is s1
True
>>> s3 is s2
False

但如果使用相等运算符:

>>> s1 == s2
True
>>> s2 == s3
True
>>> s3 == s1
True

编辑:有一个优化(无论如何,在CPython中,我不确定它是否存在于其他实现中),它允许将短字符串与is进行比较:

>>> s4 = 'hello'
>>> s5 = 'hello'
>>> id(s4)
173899104
>>> id(s5)
173899104
>>> s4 is s5
True

显然,这不是你想依赖的东西。如果要比较标识,请为作业使用适当的语句-is;如果要比较值,请使用==

你想要:

algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm == "first")

is检查对象标识(考虑内存地址)。 但在您的例子中,这些对象具有相同的“值”,但不是相同的对象。

注意==is弱。 这意味着,如果is返回True,那么==也将返回True,但反过来并不总是True。

基本上,is检查对象的地址(标识),而不是值,。对于值比较,使用==运算符

相关问题 更多 >