首页 > 编程语言 > 详细

Python index和rindex方法

时间:2019-07-02 17:36:50      阅读:77      评论:0      收藏:0      [点我收藏+]

index()方法:

描述

Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

语法

index()方法语法:

S.index(str, beg=0, end=len(string))

参数

  • S -- 父字符串
  • str -- 指定检索的字符串

  • beg -- 开始索引,默认为0。

  • end -- 结束索引,默认为字符串的长度。

返回值

如果包含子字符串返回开始的索引值,否则抛出异常。

rindex()方法:

描述

Python rindex() 方法返回子字符串最后一次出现在字符串中的索引位置,该方法与 rfind() 方法一样,只不过如果子字符串不在字符串中会报一个异常。

语法

rindex() 方法语法:

S.rindex(str, beg=0, end=len(string))

参数

  • str-- 指定检索的子字符串

  • S -- 父字符串

  • start -- 可选参数,开始查找的位置,默认为0。(可单独指定)

  • end -- 可选参数,结束查找位置,默认为字符串的长度。(不能单独指定)

返回值

返回子字符串最后一次出现在字符串中的的索引位置,如果没有匹配项则会报一个异常。

>>>S = love python!
>>>S.index(ove)
1
>>>S.sindex(ove, 2)
AttributeError                            Traceback (most recent call last)
<ipython-input-3-fef65cd971bb> in <module>()
----> 1 S.sindex(ove, 2)

AttributeError: str object has no attribute sindex
>>>S.index(ove, 1)
1
>>>S.index(ove, 1, 4)
1
>>>S.index(ove, 1, 3)
ValueError                                Traceback (most recent call last)
<ipython-input-6-49e4918571f1> in <module>()
----> 1 S.index(ove, 1, 3)

ValueError: substring not found
>>>S.rindex(o)
9
>>>S.rindex(o, 1, 5)
1
>>>S.rindex(w)
ValueError                                Traceback (most recent call last)
<ipython-input-10-5ae1ad745cf3> in <module>()
----> 1 S.rindex(w)

ValueError: substring not found

 

Python index和rindex方法

原文:https://www.cnblogs.com/ilyou2049/p/11121707.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!