📜  Python字符串 rindex() 方法

📅  最后修改于: 2022-05-13 01:55:12             🧑  作者: Mango

Python字符串 rindex() 方法

如果找到子字符串, Python String rindex() 方法返回字符串内子字符串的最高索引。否则,它会引发异常。

示例 1

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

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


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


Python3
# 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))


输出:

Substring 'geeks': 10

示例 2

Python3

# 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

Python3

# 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