当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python String rindex()用法及代码示例


如果子字符串,则rindex()方法返回字符串内子字符串的最高索引
被发现。否则会引发异常。

用法:

str.find(sub, start, end)



参数:

sub:It’s the substring which needs to be searched in the given string.
start:Starting position where sub is needs to be checked within the string.
end:Ending position where suffix is needs to be checked within the string.

注意:如果未提供开始索引和结束索引,则默认情况下它将0和length-1用作开始索引和结束索引,而我们的搜索中不包含结束索引。

返回:

Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.

例子:

input:text = 'geeks for geeks'
       result = text.rindex('geeks')
output:10

input:text = 'geeks for geeks'
       result = text.rindex('ge')
output:10

错误和异常:
ValueError:如果在目标字符串中找不到参数字符串,则会引发此错误。

代码1

# Python code to demonstrate working of rindex() 
text = 'geeks for geeks'
  
result = text.rindex('geeks') 
print("Substring 'geeks':", result)

输出:

Substring 'geeks':10

代码2

# Python code to demonstrate error by rindex() 
text = 'geeks for geeks'
  
result = text.rindex('pawan') 
print("Substring 'pawan':", result)

错误:

Traceback (most recent call last):
  File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in 
    result = text.rindex('pawan')
ValueError:substring not found

代码3

# Python code to demonstrate working of rindex() 
# with range provided 
quote = 'geeks for geeks'
  
# Substring is searched in ' geeks for geeks'  
print(quote.rindex('ge', 2)) 
  
# Substring is searched in 0 to 10 range 
print(quote.rindex('geeks', 0, 10))

输出:

10
0


相关用法


注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 String rindex() in python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。