[英]how can I print the index of the first occurrence of some characters in another string?
I'm trying to make a function made up of two strings:我正在尝试制作一个由两个字符串组成的 function :
def find_firstchars( chars, wholestring )
Which, when printed, returns the positions of each of those characters in the char string.哪个,当打印时,返回每个字符在 char 字符串中的位置。 The first character in "chars" must mark the beginning of the index for the next character, so A is indexed first, then the function carries on indexing the next character after that position, and so on. “chars”中的第一个字符必须标记下一个字符的索引的开始,因此首先索引 A,然后 function 继续索引 position 之后的下一个字符,依此类推。
There may be multiple occurrences of the "chars" string in "wholestring", but I only need to index the characters of the first one. “wholestring”中可能多次出现“chars”字符串,但我只需要索引第一个的字符。
For example,例如,
print (find_firstchars( "ABC", "VMQOAJVBKRJCPGI" )
Would return the position list: [4, 7, 11]将返回 position 列表: [4, 7, 11]
I've tried something like the code below, and beside the error I get in console for this about slice indices needing to be integers, I'm not sure how to efficiently search for each character in the following string.我已经尝试过类似下面的代码,除了我在控制台中得到的关于切片索引需要是整数的错误之外,我不确定如何有效地搜索以下字符串中的每个字符。
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"))
Though this should print [2, 6, 8].虽然这应该打印 [2, 6, 8]。
You are close:你很接近:
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.