gpt4 book ai didi

python - 字符串是否在 Python 中汇集?

转载 作者:IT王子 更新时间:2023-10-28 23:33:04 26 4
gpt4 key购买 nike

Python 是否有一个包含所有字符串的池,它们是(字符串)单例吗?

更准确地说,在下面的代码中,是在内存中创建了一个还是两个字符串?

a = str(num)
b = str(num)

最佳答案

字符串在 Python 中是不可变的,因此实现可以决定是否实习(这是一个经常与 C# 相关的术语,意味着某些字符串存储在池中)字符串。

在您的示例中,您正在动态创建字符串。 CPython 并不总是会查看池以检测字符串是否已经存在 - 这也没有意义,因为您首先必须保留内存才能创建字符串,然后将其与池内容(长字符串效率低下)。

但是对于长度为 1 的字符串,CPython 确实会查看池(参见“stringobject.c”):

static PyStringObject *characters[UCHAR_MAX + 1];

...

PyObject *
PyString_FromStringAndSize(const char *str, Py_ssize_t size)
{

...

if (size == 1 && str != NULL &&
(op = characters[*str & UCHAR_MAX]) != NULL)
{
#ifdef COUNT_ALLOCS
one_strings++;
#endif

Py_INCREF(op);
return (PyObject *)op;
}

...

所以:

a = str(num)
b = str(num)
print a is b # <-- this will print False in most cases (but try str(1) is str(1))

但是当直接在你的代码中使用constant字符串时,CPython 使用相同的字符串实例:

a = "text"
b = "text"
print a is b # <-- this will print True

关于python - 字符串是否在 Python 中汇集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2519580/

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