代码可以直接看github上的一个干净代码:https://github.com/wklken/Python-2.7.8
python内置的类型在解释器中实现,相关的内置类型见:https://docs.python.org/2/library/stdtypes.html
对应实现的类是:Objects/stringobject.c
index方法
PyDoc_STRVAR(index__doc__,
"S.index(sub [,start [,end]]) -> int\n\
\n\
Like S.find() but raise ValueError when the substring is not found.");
static PyObject *
string_index(PyStringObject *self, PyObject *args)
{
Py_ssize_t result = string_find_internal(self, args, +1);
if (result == -2)
return NULL;
if (result == -1) {
PyErr_SetString(PyExc_ValueError,
"substring not found");
return NULL;
}
return PyInt_FromSsize_t(result);
}
find方法
PyDoc_STRVAR(rfind__doc__,
"S.rfind(sub [,start [,end]]) -> int\n\
\n\
Return the highest index in S where substring sub is found,\n\
such that sub is contained within S[start:end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
static PyObject *
string_rfind(PyStringObject *self, PyObject *args)
{
Py_ssize_t result = string_find_internal(self, args, -1);
if (result == -2)
return NULL;
return PyInt_FromSsize_t(result);
}
总结:实际上内部内什么区别,就是在没有找到对应字符串,是一个异常,还是返回-1
参考资料:
https://docs.python.org/2.0/api/ Python/C API Reference Manual