python - 为什么字符串相等性不能按预期在此 Python 代码中工作?

标签 python

<分区>

注意:在你去投票或关闭我的问题,或将其标记为重复之前,让我向你保证,我已经在 SO 和 Google 上查看了很多类似的问题,但在更多一个多小时,我还是没有解决这个问题。没有其他答案可以解决我的问题。

问题 我有这个 Python 代码:

text = ''
text += '<' + '/' + '>'

print text, '</>'
print repr(text), repr('</>')

if text is '</>':
    print 'Equal'
else:
    print 'Not equal!'

我只是想比较两个字符串。出于某种原因,我需要将字符连接到 text逐个。我希望 if 语句的计算结果为 True但事实并非如此。我不知道为什么!

这是输出:

</> </> '</>' '</>' Not equal!

我是 Python 新手,正在使用 Python 2.7。有人可以帮忙吗?

最佳答案

您需要使用== 而不是isis 检查对象身份而不是相等性。

例如

假设您有 foobar:

>>> foo = 'green eggs and ham'
>>> bar = 'green eggs and ham'
>>> foo is bar
>>> False
>>> foo == bar
>>> True

在我的机器上:

>>> id(foo)
>>> 52008832 
>>> id(bar)
>>> 52010560

现在,检查一下:

>>> foobar = bar
>>> foobar is bar
>>> True

这是真的,因为我们已经将变量 foobar 别名指向 bar,这是一个引用。显然,它们在这个别名下引用了相同的位置。因此,is 返回 True。

更有趣的是,考虑两个 int。这仅适用于小整数 (-5, 256)。

>>> foo = 123
>>> bar = 123
>>> foo is bar
>>> True
>>> id(foo)
>>> 1993000432 # == id(bar)

ints (-5, 256) 被缓存,因此此范围内的 int 将评估为 true,使用 is 比较对象标识。

关于python - 为什么字符串相等性不能按预期在此 Python 代码中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36817505/

相关文章:

python - Linux环境下如何安装Python包?

python - 如何使用另一个列表拆分列表

python - 在循环中运行参数化的 pytests

python - 提取特定的文本行?

相当于 bash 的 {1..4} 的 Python 正则表达式

python - 预期的字符串或缓冲区(在 re.sub 中)

python - 带 ffill 的 GroupBy 删除组并且不将组放入索引

python - Windrose axespad 的意思

python - Airflow ETL 管道 - 在函数中使用计划日期?

python - 在图像opencv上绘制矩形?