📜  Python字符串 rfind() 方法

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

Python字符串 rfind() 方法

如果在给定的字符串中找到, Python String rfind()方法返回子字符串的最高索引。如果未找到,则返回-1。

示例 1

Python3
# Python program to demonstrate working of rfind()
# in whole string
word = 'geeks for geeks'
  
# Returns highest index of the substring
result = word.rfind('geeks')
print ("Substring 'geeks' found at index :", result )
  
result = word.rfind('for')
print ("Substring 'for' found at index :", result )
  
word = 'CatBatSatMatGate'
  
# Returns highest index of the substring
result = word.rfind('ate')
print("Substring 'ate' found at index :", result)


Python3
# Python program to demonstrate working of rfind()
# in a sub-string
word = 'geeks for geeks'
  
# Substring is searched in 'eeks for geeks'
print(word.rfind('ge', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks ', 2))
  
# Substring is searched in 's for g'
print(word.rfind('for ', 4, 11))


Python3
# Python program to demonstrate working of rfind()
# to search a string
word = 'CatBatSatMatGate'
  
if (word.rfind('Ate') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contains given substring")


输出:

Substring 'geeks' found at index : 10
Substring 'for' found at index : 6
Substring 'ate' found at index : 13

示例 2

Python3

# Python program to demonstrate working of rfind()
# in a sub-string
word = 'geeks for geeks'
  
# Substring is searched in 'eeks for geeks'
print(word.rfind('ge', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks ', 2))
  
# Substring is searched in 's for g'
print(word.rfind('for ', 4, 11))

输出:

10
10
-1
6

示例 3:实际应用

在字符串检查中很有用。检查给定的子字符串是否存在于某个字符串中。

Python3

# Python program to demonstrate working of rfind()
# to search a string
word = 'CatBatSatMatGate'
  
if (word.rfind('Ate') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contains given substring")

输出:

Doesn't contains given substring