python中rindex()方法,返回子串最后出现的位置

rindex()方法描述

python内置的字符串方法rindex()可以用于查找参数指定的字符或子串在调用对象中最后出现的索引位置,如果查找不到,则python会抛出ValueError。


rindex()语法及参数结构

str.rindex( substr, beg=0, end=len(str) )

1、第一个参数substr为str类型值,指定rindex()所要查找的字符或子串,如果不是str类型值python会抛出TypeError;2、第二个关键词参数beg指定rindex()方法查找的起始索引位置,默认为0;3、第三个参数end指定rindex()方法查找的终止索引位置,默认为调用对象str的长度。


rindex()方法返回值

索引位置值,如果查找不到,python抛出ValueError。


rindex()方法实例代码

>>> str = '笨鸟工具,x1y1z1.com'
>>> str.rindex(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> str.rindex('2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> str.rindex('1')
10
>>> str.rindex('1',0,10)
8

代码解析

1、当传递给rindex()方法一个int类型参数时,python抛出TypeError,并提示参数must be str;2、当rindex()查找不到参数指定的子串时,python抛出ValueError;3、rindex()的第三个参数终止索引位置是取不到值的,类似于数学上的开区间。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.