python中index和find有什么区别

1,549次阅读
没有评论

python中index和find有什么区别

python中,起索引作用的不止index函数,还有find函数,这两个函数有什么区别呢,下面,小编来向大家介绍一下。

一、index()

index()方法语法:

str.index(str, beg=0, end=len(string))

python index()方法检测字符串中是否包含字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定的范围内。如果包含字符串则返回开始的索引值,否则抛出异常。

使用代码:

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()方法语法:

str.find(str, beg=0, end=len(string))

python find()方法检测字符串中是否包含字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定范围内,如果包含字符串则返回开始的索引值,否则返回-1

使用代码:

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。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-17发表,共计1419字。
新手QQ群:570568346,欢迎进群讨论 Python51学习