python rindex用法_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值