如何在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP