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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM