.find()和.index()的区别

今天在复习基本数据类型——字符串的时候,有一点想法,总结一下:

字符串的定义:字符串是一个有序的字符集合,用于存储和表示基本的文字信息,用‘,“,‘’‘括起来的称之为字符串。

字符串的操作有很多种,比如索引.index(),去除.strip(),替换.replace(),切片等等。

这其中,特地取出.index()和.find()出来说明,以表区别:

首先,来官方解释:

    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.
    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

转载于:https://www.cnblogs.com/GGGGGGZX/p/8903707.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值