如何在Python中向后查找字符串?
在本文中,我们将了解如何在 Python 中向后查找字符串。
第一种方法是使用内置的 python String 类的 rindex() 方法。Python 字符串 rindex() 方法返回给定字符串中任何子字符串的最高索引。
通过最高索引,我们的意思是,如果给定子字符串在字符串中出现两次或三次, rindex() 方法将返回子字符串最右侧或最后一次出现的索引。
这个函数的主要缺点是,如果字符串不包含子字符串,则抛出异常。
阅读更多:Python 教程
示例1
在下面给出的示例中,我们输入一个字符串,然后使用 rindex() 方法找出某些特定字符的最后一个索引。
str1 = "Welcome to Tutorialspoint"
char = "Tutorial"
print("The given string is:")
print(str1)
print("Finding the last index of",char)
print(str1.rindex(char))
输出
上面示例的输出如下所示−
The given string is:
Welcome to Tutorialspoint
Finding the last index of Tutorial
11
示例2
在下面给出的示例中,我们采取与上面同样的程序,但我们尝试不同的字符串作为输入。
str1 = "Welcome to Tutorialspoint"
char = "Hello"
print("The given string is:")
print(str1)
print("Finding the last index of",char)
print(str1.rindex(char))
输出
上面示例的输出如下−
The given string is:
Welcome to Tutorialspoint
Finding the last index of Hello
Traceback (most recent call last):
File "C:\Users\Tarun\OneDrive\Desktop\practice.py", line 6, in
print(str1.rindex(char))
ValueError: substring not found
使用rfind()方法
有一个叫做 rfind() 的方法,它可以用来克服 rindex() 的缺点。它的功能与 rindex() 方法类似,但不同的是,如果在字符串中未找到给定的子字符串,此方法返回 “-1″,表示未找到给定的子字符串。
示例1
在下面给出的示例中,我们输入一个字符串,然后使用 rfind() 方法找出某些特定字符的最后一个索引。
str1 = "Welcome to Tutorialspoint"
char = "Tutorial"
print("The given string is:")
print(str1)
print("Finding the last index of",char)
print(str1.rfind(char))
输出
上面示例的输出如下所示−
The given string is:
Welcome to Tutorialspoint
Finding the last index of Tutorial
11
示例2
在下面给出的示例中,我们采取与上面相同的程序,但我们尝试不同的字符串作为输入。
str1 = "Welcome to Tutorialspoint"
char = "Hello"
print("The given string is:")
print(str1)
print("Finding the last index of",char)
print(str1.rfind(char))
输出
上面示例的输出如下所示−
The given string is:
Welcome to Tutorialspoint
Finding the last index of Hello
-1
极客教程