当你比较 python 中的两个字符串时会发生什么

what happens when you compare two strings in python

比较 python 中的字符串时,例如

if "Hello" == "Hello":
    #execute certain code

我很好奇比较字符串的代码是什么。因此,如果我要在 c 中比较这些,我只会比较每个字符并在一个字符不匹配时中断。我想知道像这样比较两个字符串的确切过程是什么,即它何时会中断以及这种比较与上述方法之间是否有任何区别,除了代码行中的冗余

我假设您在这里使用 CPython,即标准 Python.org 实现。在幕后,Python 字符串类型是在 C 中实现的,所以是的,测试两个字符串是否相等的方式与在 C 中完全相同。

它的作用是使用 memcmp() function to test if the two str objects contain the same data, see the unicode_compare_eq function defined in unicodeobject.c:

static int
unicode_compare_eq(PyObject *str1, PyObject *str2)
{
    int kind;
    void *data1, *data2;
    Py_ssize_t len;
    int cmp;

    len = PyUnicode_GET_LENGTH(str1);
    if (PyUnicode_GET_LENGTH(str2) != len)
        return 0;
    kind = PyUnicode_KIND(str1);
    if (PyUnicode_KIND(str2) != kind)
        return 0;
    data1 = PyUnicode_DATA(str1);
    data2 = PyUnicode_DATA(str2);

    cmp = memcmp(data1, data2, len * kind);
    return (cmp == 0);
}

只有当 str1str2 不是同一个对象时才会调用此函数(这是一个简单且便宜的测试方法)。它首先检查两个对象是否长度相同,存储的数据是否相同(字符串对象使用flexible storage implementation节省内存;不同的存储意味着字符串不能相等)。

还有其他 Python 实现,例如 Jython 或 IronPython,它们可能使用不同的技术,但基本上可以归结为相同的东西。