在下面的代码示例中,我们将演示如何使用Python中的字符串操作来实现部分字符串搜索。
def partial_string_search(string, substring):
indexes = []
start = 0
while True:
index = string.find(substring, start)
if index == -1:
break
indexes.append(index)
start = index + 1
return indexes
# 示例用法
string = "This is a test string. This is another test string."
substring = "test"
indexes = partial_string_search(string, substring)
print("Occurrences of '{}' in '{}':".format(substring, string))
for index in indexes:
print("Index: ", index)
print("Substring: ", string[index:index+len(substring)])
在上述代码中,partial_string_search
函数接受两个参数:string
和substring
。它使用find
方法来查找substring
在string
中的位置,并将每次找到的位置记录在indexes
列表中。find
方法返回-1表示未找到。然后,我们可以遍历indexes
列表,打印每个匹配的索引和对应的子字符串。
运行上述代码将输出:
Occurrences of 'test' in 'This is a test string. This is another test string.':
Index: 10
Substring: test
Index: 33
Substring: test
这表示在给定字符串中,子字符串"test"出现在索引位置10和33。