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