如何在Python中查詢字串中子字串的第n次出現?


在本文中,我們將瞭解如何在Python中查詢字串中子字串的第n次出現。

第一種方法是使用split()方法。我們必須定義一個函式,其引數為字串、子字串和整數n。透過最多n+1次分割子字串,可以找到字串中子字串的第n次出現。

如果結果列表的大小大於n+1,則子字串出現次數超過n次。原始字串的長度減去最後一個分割段的長度等於子字串的長度。

示例

在下面的示例中,我們以字串和子字串作為輸入,並使用split()方法查詢字串中子字串的第n次出現

def findnth(string, substring, n):
   parts = string.split(substring, n + 1)
   if len(parts) <= n + 1:
      return -1
   return len(string) - len(parts[-1]) - len(substring)
   
string = 'foobarfobar akfjfoobar afskjdf foobar'
print("The given string is")
print(string)

substring = 'foobar'
print("The given substring is")
print(substring)

res = findnth(string,substring,2)
print("The position of the 2nd occurence of the substring is")
print(res)

輸出

上述示例的輸出如下所示:

The given string is
foobarfobar akfjfoobar afskjdf foobar
The given substring is 34. How to find the nth occurrence of substring in a string in Python
foobar
The position of the 2nd occurence of the substring is
31

使用find()方法

第二種方法是使用find()方法。此方法執行出現次數,並返回最終結果。

示例

在下面的示例中,我們以字串和子字串作為輸入,並查詢字串中子字串的第n次出現

string = 'foobarfobar akfjfoobar afskjdf foobar'

print("The given string is")
print(string)

substring = 'foobar'
print("The given substring is")
print(substring)
n = 2
res = -1
for i in range(0, n):
   res = string.find(substring, res + 1)
print("The position of the 2nd occurence of the substring is")
print(res)

輸出

上述示例的輸出如下所示:

The given string is
foobarfobar akfjfoobar afskjdf foobar
The given substring is
foobar
The position of the 2nd occurence of the substring is
16

更新於:2022年12月7日

4K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告