Python index和rindex方法

时间:2019-07-02 17:36:50   收藏:0   阅读:77

index()方法:

描述

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

语法

index()方法语法:

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

参数

返回值

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

rindex()方法:

描述

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

语法

rindex() 方法语法:

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

参数

返回值

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

>>>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

 

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!