Python番外(0005): 字符串find()方法和index()方法的区别

本文探讨了Python内置字符串find()和index()方法在查找子串位置上的不同:find()返回-1未找到时不会报错,而index()会引发ValueError。理解这俩函数在错误处理上的差异有助于避免程序中断。
摘要由CSDN通过智能技术生成

众所周知,字符串的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()的时候,如果没有做错误处理,那么有可能会导致程序报错之后停止运行。

image-20210206171637316

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值