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