gpt4 book ai didi

Python 字符串末尾有空格和没有空格且不可变

转载 作者:太空狗 更新时间:2023-10-29 19:35:56 24 4
gpt4 key购买 nike

我了解到在某些不可变类中,__new__ 可能会返回一个现有实例 - 这就是 intstr tuple 类型有时对小值有用。

但为什么以下两个片段的行为不同?

最后一个空格:

>>> a = 'string '
>>> b = 'string '
>>> a is b
False

没有空格:

>>> c = 'string'
>>> d = 'string'
>>> c is d
True

为什么空间会带来差异?

最佳答案

这是 CPython 实现如何选择缓存字符串文字的一个怪癖。具有相同内容的字符串字面值可能指的是同一个字符串对象,但它们不是必须的。 'string' 恰好在 'string ' 不是时被自动驻留,因为 'string' 仅包含 Python 标识符中允许的字符。我不知道为什么这是他们选择的标准,但确实如此。在不同的 Python 版本或实现中,行为可能不同。

来自 CPython 2.7 源代码,stringobject.h , 第 28 行:

Interning strings (ob_sstate) tries to ensure that only one string object with a given value exists, so equality tests can be one pointer comparison. This is generally restricted to strings that "look like" Python identifiers, although the intern() builtin can be used to force interning of any string.

您可以在 Objects/codeobject.c 中看到执行此操作的代码:

/* Intern selected string constants */
for (i = PyTuple_Size(consts); --i >= 0; ) {
PyObject *v = PyTuple_GetItem(consts, i);
if (!PyString_Check(v))
continue;
if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
continue;
PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
}

另请注意,实习是一个独立于 Python 字节码编译器合并字符串文字的过程。如果您让编译器将 ab 赋值编译在一起,例如通过将它们放在模块或 if True: 中,您会发现 ab 将是相同的字符串。

关于Python 字符串末尾有空格和没有空格且不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21203212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com