python序列类型字符串的方法L.index()与L.find()区别

Posted 20web-刘威-竹雨听闲-PY201801112

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python序列类型字符串的方法L.index()与L.find()区别相关的知识,希望对你有一定的参考价值。

首先官方解释

    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

可以看到S.index()与S.find()类似,不过索引字符串中的子串没找到会报错。

而S.find()在找不到substring时,不会报错,而会返回-1

 

总结:

s.index(x):返回字符串中出现x的最左端的索引值,如果不在则抛出valueError异常

s.find(x) :返回字符串中出现x的最左端字符的索引值,如果不在则返回-1

 

 

以上是关于python序列类型字符串的方法L.index()与L.find()区别的主要内容,如果未能解决你的问题,请参考以下文章