我正在尝试创建一个程序,该程序将列出子字符串在父字符串中出现的位置。例如,假设我们在父字符串“abcabcabcabcabcabca”中搜索“bc”,程序将返回 1、4、7、10、13、16。
到目前为止,我一直在使用:
import string
def subStringMatchExact():
print "This program will index the locations a given sequence"
print "occurs within a larger sequence"
seq = raw_input("Please input a sequence to search within: ")
sub = raw_input("Please input a sequence to search for: ")
n = 0
for i in seq:
x = string.find(seq, sub [n:])
print x
n = x + 1
我还尝试用 string.index 运算符替换 string.find。任何建议将不胜感激。
最佳答案
只需调用 .find()
在输入字符串本身上。如果未找到匹配项,它将返回匹配项的位置或 -1
。它还需要一个start 参数,因此您可以查找下一个 匹配项:
def subStringMatchExact():
print "This program will index the locations a given sequence"
print "occurs within a larger sequence"
seq = raw_input("Please input a sequence to search within: ")
sub = raw_input("Please input a sequence to search for: ")
positions = []
pos = -1
while True:
pos = seq.find(sub, pos + 1) # start searching *beyond* the previous match
if pos == -1: # Not found
break
positions.append(pos)
return positions
关于Python:索引子字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056856/