Python程序,用于查找给定字符串在另一个给定字符串中出现的第三个位置



如何找到Python程序来找到给定字符串在另一个给定字符串中出现的第三个位置。

find_string("I am the the champion of the champions of the champions", "the")

您可以使用这样的正则表达式在'haystack'中查找'needle'

import re
haystack = "I am the the champion of the champions of the champions"
needle = "the"

# print all matches
for i, match in enumerate(re.finditer(needle, haystack)):
print(f"{i+1}, start:{match.start()}, end:{match.end()}")
# or select the third from a list
matches = list(re.finditer(needle, haystack))  # list of all matches
matches[2].start()  # get start position of third match
matches[2].end()  # get end position of third match

编辑:仅使用str.find

def find_nth(haystack, needle, n):
start, lneedle = haystack.find(needle), len(needle)
for _ in range(n-1):
start = haystack.find(needle, start + lneedle)
return start
find_nth(haystack, needle, 3)

你可以这样做,

def find_string(txt, str1, n):
index = 0
for i in range(n + 1):
index = txt.find(str1, index + 1)
return txt.find(str1, index)

输出:

find_string("I am the the champion of the champions of the champions", "the", 3)
# Output
# 42

最新更新