如何打印另一个字符串中某些字符首次出现的索引



我正在尝试制作一个由两个字符串组成的函数:

def find_firstchars( chars, wholestring )

打印时,返回字符字符串中每个字符的位置。"中的第一个字符;字符";必须为下一个字符标记索引的开始,因此首先对A进行索引,然后函数继续对该位置之后的下一个字符串进行索引,依此类推

可能存在多次出现的";字符";字符串在";"整串";,但我只需要索引第一个字符。

例如,

print (find_firstchars( "ABC", "VMQOAJVBKRJCPGI" )

将返回职位列表:[4,7,11]

我尝试过下面的代码,除了控制台中关于切片索引必须是整数的错误外,我不知道如何有效地搜索下面字符串中的每个字符。

def find_firstchars(chars, wholestring):
index = 0 # Initializing index
splice = [] # Initializing list
while index != -1: # Run until at end of index
index = chars.find(chars,wholestring) # Finds index value of each char in subsequence
if index != -1: # If not at end:
splice.append(index) # Append index value to splice list,
index += 1 # Then keep looking
return splice
print (find_firstchars("GTA", "ACGACATCACGTGACG"))

尽管这应该打印[2,6,8]。

您已接近:

def find_firstchars(chars, wholestring):
index = 0 # Initializing index
splice = [] # Initializing list
for c in chars:
index = wholestring.find(c,index)
splice.append(index)
index += 1 # Then keep looking
return splice
print (find_firstchars("GTA", "ACGACATCACGTGACG"))

最新更新