我有這兩個字串:
t = 'GATATCATGCATATACTT'
s = 'ATAT'
我正在嘗試創建一個函式,該函式在串列中回傳在字串 t 的序列中找到字串 s 的原因的位置。也就是說,在這種情況下,位置將是 [1, 10]。而且,如果找不到原因,串列將回傳 [-1]。
def search_motif (t, s):
search_motif = list()
for i, x in enumerate(t):
if s in x:
search_motif.append(i)
i = 1
return [-1] # this must go to the end
print (search_motif (t, s))
我走對了路嗎?有人可以指導我嗎?
uj5u.com熱心網友回復:
使用正則運算式似乎是一種更好的方法。
import re
def search_motif(t, s):
p = re.compile(s)
motif = []
for mo in p.finditer(t):
motif.append(mo.start())
if motif:
return motif
else:
return -1
編輯:mo.span()[0] --> mo.start()
uj5u.com熱心網友回復:
您可以為此使用str.index
>>> def findall(text,subtext):
i=0
ind=[]
while True:
try:
i = text.index(subtext,i) #the second argument tell where to start looking for the sub string
ind.append(i)
i =1 #for the next iteration we start looking in the immediate next index
except ValueError: #we break when no more occurrences are found
break
if i==0: #we check if we didn't found a match before
ind.append(-1)
return ind
>>> t = 'GATATCATGCATATACTT'
>>> s = 'ATAT'
>>> findall(t,s)
[1, 10]
>>> findall(t,"X")
[-1]
>>>
現在關于您的代碼,它不起作用有兩個原因:第一個是您沒有回傳您創建的串列,第二個是因為您正在查看單個字符
>>> for i,x in enumerate("HELLO"):
print(x)
H
E
L
L
O
>>>
如果你不是在尋找一個角色,你永遠不會得到匹配
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388321.html
