str.split 的源代码?

joh*_*ual 6 python python-2.7 python-internals

我想看看str.split()在 Python 中是如何实现的这是我尝试过的:

> inspect.getsource(str.split)

TypeError: <method 'split' of 'str' objects> is not a module, 
class, method, function, traceback, frame, or code object
Run Code Online (Sandbox Code Playgroud)

复制 StackOverflow 上的另一个示例不起作用:Python 中最大公约数的代码

Jim*_*ard 8

inspect.getsource(str.split)不是为了处理以实现语言(C此处)编写的代码而编写的。str.split内置的,即用C.

实现的源代码str.split根据是否提供sep参数分为两部分。

第一个函数sepsplit_whitespace. 它的实施方式非常简单。主要块位于while删除前导空格的循环中,如果存在任何空格并在其上拆分,则搜索剩余的字符串字符。我添加了一些注释来说明这一点:

i = j = 0;
while (maxcount-- > 0) {
    /* Increment counter past all leading whitespace in 
       the string. */
    while (i < str_len && STRINGLIB_ISSPACE(str[i]))
        i++;
    /* if string only contains whitespace, break. */
    if (i == str_len) break;

    /* After leading white space, increment counter 
       while the character is not a whitespace. 
       If this ends before i == str_len, it points to 
       a white space character. */
    j = i; i++;
    while (i < str_len && !STRINGLIB_ISSPACE(str[i]))
        i++;
#ifndef STRINGLIB_MUTABLE
    /* Case where no split should be done, return the string. */
    if (j == 0 && i == str_len && STRINGLIB_CHECK_EXACT(str_obj)) {
        /* No whitespace in str_obj, so just use it as list[0] */
        Py_INCREF(str_obj);
        PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
        count++;
        break;
    }
#endif
    /* Make the split based on the incremented counters. */
    SPLIT_ADD(str, j, i);
}
Run Code Online (Sandbox Code Playgroud)

类似地,split_char是将字符作为 提供的情况sep。它的实现再次非常简单,看到后检查一下split_whitespace;你不会觉得太难。

还有处理分隔符长度超过一个字符的情况的split功能。这是通过搜索字符串中的字符并相应地拆分来实现的。