ilyou2049

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

 

分类:

技术点:

相关文章:

  • 2021-12-19
  • 2021-12-29
  • 2021-12-29
  • 2021-12-19
  • 2021-12-19
  • 2021-12-29
  • 2021-08-03
  • 2021-12-19
猜你喜欢
  • 2021-12-19
  • 2021-12-19
  • 2021-12-19
  • 2021-12-19
  • 2021-12-19
  • 2021-12-19
  • 2021-12-19
相关资源
相似解决方案