python - sys.intern() 无法在切片时实习字符串

标签 python string identity python-internals

为什么 sys.intern() 无法实习该字符串?

>>> from sys import intern
>>> "abcd"[:-1] == "abc"
True
>>> "abcd"[:-1] is "abc"
False
>>> intern("abc")
'abc'
>>> "abcd"[:-1] is "abc"
False  # Expected True

(在 CPython 3.7.4 上)

最佳答案

字符串文字已经被保留,它是您需要手动保留的计算表达式。

from sys import intern
print("abcd"[:-1] is "abc")  # False
print(intern("abcd"[:-1]) is "abc")  # True
print("abcd"[:-1] is "abc")  # False

intern 并不意味着“每当程序中的任何位置生成此字符串时,都将其更改为驻留引用”,它只是返回给定字符串的驻留引用。

s1 = "abc"
s2 = "abc"
s3 = "abcd"[:-1]
s4 = intern(s3)
for s in [s1, s2, s3, s4]:
  print(id(s))
140002991598512
140002991598512
140002990838576
140002991598512

关于python - sys.intern() 无法在切片时实习字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67947294/

相关文章:

python - 通过指定行/列从现有矩阵创建新矩阵

python - 编程错误: Incorrect number of bindings supplied

python - 如何在 python 中使用比较符号进行输入

python - python中的多项式样本生成

c# - 将 id 标识值存储在变量中

java - 将 MAC 地址字节数组格式化为字符串

Python翻译多个字符

python - 在python中比较字符串时忽略空格

java - 有没有我可以使用的 Map 来防止 .equals() 重复?

C# .NET 核心获取当前用户 ID 的最佳方式