Python 如何找到字符串中子字符串的最后一次出现的索引
字符串是由字符组成的集合,可以表示一个单词或整个句子。在Python中,我们可以声明一个字符串或任何其他数据类型而不使用数据类型说明符。因此,与Java相比,使用字符串在Python中更容易。
字符串是String类的一个对象,该类包含多个用于操作和访问字符串的方法。
在本文中,我们将重点讨论如何在Python中找到字符串中子字符串的最后一次出现的索引。
使用rindex()方法
一种找到子字符串最后一次出现的索引的方法是使用内置的Python String类的 rindex() 方法。它接受一个表示要查找的子字符串的参数,并返回当前字符串中给定字符串的最后一个索引。
这个函数的主要缺点是,如果在字符串中没有子字符串,它会抛出一个异常。
为了克服 rindex() 的局限性,还有一个名为 rfind() 的函数。它的功能与 rindex() 类似,但是如果在字符串中没有给定的子字符串,该方法不会返回异常,而是返回“1”,表示给定的子字符串不存在。
rindex() 和 rfind() 都有可选参数,您可以在这些参数中指定要开始搜索的起始索引和结束索引。
示例1
在下面给出的示例中,我们使用 rindex() 方法找出给定字符串中字符“t”的最后一次出现。
str1 = "Welcome to tutorialspoint"
index = str1.rindex('t')
print("The last index of t in the given string is",index)
输出
以上示例的输出如下:
('The last index of t in the given string is', 24)
示例2
在下面的示例中,我们试图使用rindex()方法找出给定字符串中字符’d’的最后一个索引,但该字符串中不存在字符’d’。
str1 = "Welcome to tutorialspoint"
index = str1.rindex('d')
print("The last index of t in the given string is",index)
输出
上述示例的输出为:
Traceback (most recent call last):
File "main.py", line 3, in
index = str1.rindex('d')
ValueError: substring not found
示例3
在下面给出的示例中,我们使用了方法 rfind() 来找到给定字符串中字符 t 的最后一次出现。
str1 = "Welcome to tutorialspoint"
index = str1.rfind('t')
print("The last index of t in the given string is",index)
输出
上述示例的输出是:
('The last index of t in the given string is', 24)
示例4
在下面的示例中,我们尝试使用rfind()方法找出给定字符串中字符’d’的最后一个索引,但是该字符串中不存在字符’d’。
str1 = "Welcome to tutorialspoint"
index = str1.rfind('d')
print("The last index of t in the given string is",index)
输出
上面示例的输出如下:
('The last index of t in the given string is', -1)