
我们在使用表格的时候,通常会创建索引,索引可以大大加快数据的检索速度,加快表与表之间的连接。在使用分组和排序时,子句进行数据检索可以明显减少查询中分组和排序的时间。之前小编向大家介绍过在列表起索引作用的index() 函数(https://www.py.cn/jishu/jichu/21636.html)。其实在python中,起索引作用的不止index函数,还有find函数,这两个函数有什么区别呢,下面,小编来向大家介绍一下。
一、index()
index()方法语法:
1 | str.index(str, beg=0, end =len(string))
|
python index()方法检测字符串中是否包含字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定的范围内。如果包含字符串则返回开始的索引值,否则抛出异常。
使用代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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()
find()方法语法:
1 | str.find(str, beg=0, end =len(string))
|
python find()方法检测字符串中是否包含字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定范围内,如果包含字符串则返回开始的索引值,否则返回-1
使用代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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);
}
|
通过小编这么一对比,你知道index函数和find函数有什么区别了吗?实际上这俩者内部并没有什么区别,只不过是在没有找到对应字符串,是一个异常,还是返回-1。