如何在 Python 中反向搜尋字串?
在本文中,我們將瞭解如何在 Python 中反向搜尋字串。
第一種方法是使用內建的 Python 字串類的rindex()方法。Python 字串rindex()方法返回給定字串中任何子字串的最高索引。
最高索引是指,如果給定的子字串在一個字串中出現兩次或三次,則rindex()方法將返回該子字串最右邊或最後一次出現的索引。
此函式的主要缺點是,如果字串不包含任何子字串,它將丟擲異常。
示例 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, inprint(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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP