网站首页 > 知识剖析 正文
string.rindex()方法
string.rindex()方法返回字符串内子字符串的最高索引(如果找到)。 如果未找到子字符串,则会引发异常。
rindex()的语法为:
str.rindex(sub [,start [,end]])
string.rindex()参数
rindex()方法采用三个参数:
- sub-要在str字符串中搜索的子字符串。
- start和end(是可选参数)-在str [start:end]中搜索子字符串
从rindex()返回值:
- 如果字符串中存在子字符串,则它将返回字符串中找到子字符串的最高索引。
- 如果子字符串在字符串中不存在,则会引发ValueError异常。
rindex()方法类似于字符串的rfind()方法(后面我会写到符串的rfind()方法)
唯一的区别是,如果未找到子字符串,则rfind()返回-1,而rindex()则引发异常。
下面将直接举例说明与理解:
示例1:没有start 和 end参数的rindex():
quote = 'Let it be, let it be, let it be'
result = quote.rindex('let it')
print("Substring 'let it':", result)
result = quote.rindex('small')
print("Substring 'small ':", result)
输出:
Substring 'let it': 22
Traceback (most recent call last):
File "...", line 6, in <module>
result = quote.rindex('small')
ValueError: substring not found
注意:Python中的索引从0开始,而不是1
示例2:带有start 和 end参数的rindex():
quote = 'Do small things with great love'
print(quote.rindex('t', 2))
print(quote.rindex('th', 6, 20))
print(quote.rindex('o small ', 10, -1))
输出:
25
18
Traceback (most recent call last):
File "...", line 10, in <module>
print(quote.rindex('o small ', 10, -1))
ValueError: substring not found
你学会了吗?
欢迎在下面留言讨论,
谢谢关注.
猜你喜欢
- 2024-11-13 pandas如何操作Excel?还不会的,看此一篇足矣
- 2024-11-13 买不到口罩怎么办?Python 爬虫帮你时刻盯着自动下单!| 原力计划
- 2024-11-13 [oeasy]python0078_设置索引颜色_index_color_ansi_控制终端颜色
- 2024-11-13 Python基础教程:新手朋友在python中常见的错误信息汇总
- 2024-11-13 python index ValueError: substring not found
- 2024-11-13 将多行多列的数据拆分成多行一列的数据(index函数)
- 2024-11-13 Python数据分析实战-Series转DataFrame并将index设为新的一列
- 2024-11-13 盘点Python 初学者最容易犯的10大错误!你中招了吗?
- 2024-11-13 1-6,0基础学Python创建list,Python中布尔类型按照索引访问list
- 2024-11-13 Python之序列 python 序列
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)