如何在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)

更新於:2022年10月19日

14K+ 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告