【问题标题】:Why "`trade".replace("`", "") is "trade" resulting False and "".join(list("`trade")[1:]) is "trade" also False [duplicate]为什么 "`trade".replace("`", "") 是 "trade" 导致 False 并且 "".join(list("`trade")[1:]) 是 "trade" 也是 False [重复]
【发布时间】:2021-09-25 00:50:34
【问题描述】:

我想知道为什么以下测试返回 False: 假设我有 2 个简单的字符串:

str0 = "trade"
str1 = "`trade"

我不明白为什么 python 中的以下测试返回 False:

str1.replace("`", "") is str0 

还有,

"".join(list(str1)[1:]) is str0 => False

感谢您的教育!

【问题讨论】:

  • 这是由于解释器的优化。始终使用== 来比较值!
  • 几乎总是使用== 来比较值。 None、True 和 False 都是具有单一身份的单例。

标签: python string str-replace string-comparison


【解决方案1】:

在 Python 中,is 比较内存中的两个对象,== 比较它们的值。由于您的两个变量存储在内存中的两个不同位置,因此您使用 is 的比较结果为 false。

【讨论】:

    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多