📌  相关文章
📜  Python|查找最后一次出现的子字符串

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

Python|查找最后一次出现的子字符串

有时,在处理字符串时,我们需要查找字符串中是否存在子字符串。这个问题很常见,之前已经讨论过很多次了。这里讨论了获取字符串最后一次出现的变化。让我们讨论可以执行此操作的某些方式。

方法 #1:使用rindex()

如果字符串中存在子字符串,此方法将返回最后一次出现的子字符串。这个函数的缺点是,如果字符串中没有子字符串,它会抛出异常,从而破坏代码。

# Python3 code to demonstrate
# Find last occurrence of substring
# using rindex()
  
# initializing string 
test_string = "GfG is best for CS and also best for Learning"
  
# initializing target word 
tar_word = "best"
  
# printing original string 
print("The original string : " + str(test_string))
  
# using rindex()
# Find last occurrence of substring
res = test_string.rindex(tar_word)
  
# print result
print("Index of last occurrence of substring is : " + str(res))
输出 :
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

方法 #2:使用rfind()

这是执行此任务的替代方法。该函数比上述方法提供的优势在于,如果未找到子字符串,该函数将返回“-1”,而不是抛出错误。

# Python3 code to demonstrate
# Find last occurrence of substring
# using rfind()
  
# initializing string 
test_string = "GfG is best for CS and also best for Learning"
  
# initializing target word 
tar_word = "best"
  
# printing original string 
print("The original string : " + str(test_string))
  
# using rfind()
# Find last occurrence of substring
res = test_string.rfind(tar_word)
  
# print result
print("Index of last occurrence of substring is : " + str(res))
输出 :
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28