可能是重复问题:
Python中的字符串比较:is vs. ==
algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm is "first")
我正在使用命令行并带有参数first
运行它,那么为什么这段代码会输出:
first
False
可能是重复问题:
Python中的字符串比较:is vs. ==
algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm is "first")
我正在使用命令行并带有参数first
运行它,那么为什么这段代码会输出:
first
False
>>> 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,但反之不一定成立。
==
测试比较对象是否具有相同的值,而 is
测试它们是否具有相同的 id
(大致等同于内存位置)。 - Sam Mussmanna = 'a'; b='a'; a is b"
是正确的。 - Jon Clementsa
和b
指向内存中的同一位置,因此它们是相同的。 - Dmitry Shevchenkois
检查对象的地址(身份标识),而不是值。如果要进行值比较,请使用 ==
运算符。