str.split的源代码?

时间:2016-10-30 19:28:38

标签: python python-2.7 python-internals

我想看看如何在Python中实现str.split()以下是我尝试的内容:

> inspect.getsource(str.split)

TypeError: <method 'split' of 'str' objects> is not a module, 
class, method, function, traceback, frame, or code object

在StackOverflow上复制另一个示例无效:Code for Greatest Common Divisor in Python

1 个答案:

答案 0 :(得分:2)

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

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

第一个函数是split_whitespace,当没有提供sep参数并且拆分删除空白字符时。如何实施是非常直截了当的;主体积位于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);
}

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

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

相关问题