1. 程式人生 > >python序列類型字符串的方法L.index()與L.find()區別

python序列類型字符串的方法L.index()與L.find()區別

splay where substr fail arguments str ont spa tar

首先官方解釋

    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()區別