如何在 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP