众所周知,字符串的find()
和index()
都可以查询某个字符或者某段字符在字符串中的位置,那么这两者有什么区别吗?
先看看官方的函数注释:
- find()
find(...) method of builtins.str instance
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.
- index()
index(...) method of builtins.str instance
S.index(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.
Raises ValueError when the substring is not found.
对比之后发现,两个注释只有最后一行不同。如果要查询的字符在字符串中找不到,那么find()
方法会返回-1
,并不会报错,而index()
会直接报错(ValueError)。因此,使用index()
的时候,如果没有做错误处理,那么有可能会导致程序报错之后停止运行。